【问题标题】:Problem with extension method with asp.net web form page code behind带有asp.net web表单页面代码的扩展方法存在问题
【发布时间】:2019-10-17 23:54:30
【问题描述】:

我正在创建一个扩展方法来使用 c# 检查空数据行,我正在尝试在我的 asp.net Web 表单代码中使用扩展方法,但告诉我 IsEmpty 方法在当前上下文中不存在 这是我正在尝试的代码

 public static class IsNullValidator
    {
        public static bool IsNullEquivalent( this object value)
        {
            return value == null
                   || value is DBNull
                   || string.IsNullOrWhiteSpace(value.ToString());
        }
        public static bool IsEmpty( this DataRow row)
        {
            return row == null || row.ItemArray.All(i => i.IsNullEquivalent());
        }
    }

我这样称呼它

DataRow[] row =getRowMethod();
if IsEmpty(row){"do some functionality"}

如果我通过将这个关键字删除到下面来更改 IsEmpty 签名,它的工作原理是这样的

   public static bool IsEmpty(  DataRow row)
            {
                return row == null || row.ItemArray.All(i => i.IsNullEquivalent());
            }
   if IsEmpty(row[0]){"do some functionality"}

我需要使用此扩展程序来检查任何数据行,并在将来检查任何数据表 我可以使用下面的方法来检查空数据表吗

 public static bool IsEmptyDatatable (DataTable dt)
    {
        return dt == null || dt.Rows.Cast<DataRow>().Where(r=>r.ItemArray[0]!=null).All(i => i.IsNullEquivalent());
    }

【问题讨论】:

  • 当遇到此类问题时,我通常会使用临时变量将代码拆分为多行。这样我就可以依次调试每个操作并获得正确的异常消息。没有什么可担心的性能。 JiT 编译器完全能够切割未充分利用的变量。如果有的话,通常是好的。即使有,代码的可读性和可调试性也可能胜过那一点点差异。
  • 我使用的是 c# 编译器而不是 jit ,并且在编码时调用方法的问题不是在运行时
  • 即时编译器由运行时在 MSIL 上运行,在它接近 CPU 之前。所以它在这里完全适用。 en.wikipedia.org/wiki/Just-in-time_compilation
  • 这就是你不使用扩展方法的方式。 docs.microsoft.com/en-us/dotnet/csharp/programming-guide/…
  • 如果它是一个扩展方法,你应该把它称为row[0].IsEmpty()。这就是为什么它被称为扩展方法,因为它使用新的方法扩展了一个类型。您只需确保使用正确的 using 语句导入静态类。

标签: c# asp.net webforms ado


【解决方案1】:

扩展方法是一种类型的“扩展”。在您的情况下,您正在扩展 DataRow 类。对于扩展方法,您需要有一个该类的实例来调用它,例如:

DataRow[] row =getRowMethod();

if row.IsEmpty(){"do some functionality"}

在示例中,扩展方法是在DataRow 类的实例row 上调用的。

如果您认为 this 关键字表示“可以在 'this' 类的实例上调用此方法” - 在您的情况下是 DataRow,这可能有助于您理解它。

【讨论】:

  • 是的,正如@Jacob 提到的,如果row[0].IsEmpty(){"do some functionality"} 并且它可以工作,我将其更改为下面,但仍然面临检查空数据表的第二个问题,我最终得到了这个公共静态布尔 IsEmptyDatatable(这个 DataTable dt ) { return dt == null || dt.Rows.Cast&lt;DataRow&gt;().All(i =&gt; i.IsEmptyDataRow()); }
【解决方案2】:

最后我得到了下面的解决方案,谢谢大家......你的建议都很有帮助

 public static bool IsNullEquivalent( this object value)
        {
            return value == null
                   || value is DBNull
                   || string.IsNullOrWhiteSpace(value.ToString());
        }
        public static bool IsEmptyDataRow(this  DataRow row)
        {
            return row == null || row.ItemArray.All(i => i.IsNullEquivalent());
        }
        public static bool IsEmptyDatatable (this DataTable dt)
        {
            return dt == null || dt.Rows.Cast<DataRow>().All(i => i.IsEmptyDataRow());
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 2017-08-24
    • 2019-03-16
    • 1970-01-01
    相关资源
    最近更新 更多