C# 扩展

标签 c# extension-methods

我通常非常谨慎地使用扩展方法。当我确实觉得有必要编写一个扩展方法时,有时我想重载该方法。我的问题是,您对调用其他扩展方法的扩展方法有何看法?不好的做法?感觉不对,但我无法真正定义原因。

例如,第二个 CaselessIs 方法调用第一个:

public static bool CaselessIs(this string s, string compareTo)
{
    return string.Compare(s, compareTo, true) == 0;
}

public static bool CaselessIs(this string s, IEnumerable<string> compareTo)
{
    foreach(string comparison in compareTo)
    {
        if (s.CaselessIs(comparison))
        {
            return true;
        }
    }

    return false;
}

不这样做会更合适吗?缺点是它违反了 DRY。

public static bool CaselessIs(this string s, string compareTo)
{
    return string.Compare(s, compareTo, true) == 0;
}

public static bool CaselessIs(this string s, IEnumerable<string> compareTo)
{
    foreach(string comparison in compareTo)
    {
        if (string.Compare(s, comparison, true) == 0)
        {
            return true;
        }
    }

    return false;
}

最佳答案

我不得不说这里是 DRY 控件。就个人而言,我认为调用另一个扩展方法的扩展方法没有任何问题,特别是如果另一个扩展包含在同一个程序集中。总而言之,方法调用只是由编译器翻译自:

extended.ExtensionMethod(foo);

到:

StaticType.ExtensionMethod(extended, foo);

我没有看到将两个静态方法链接在一起有任何问题,因此传递性地,我没有看到链接两个扩展方法有问题。

关于C# 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/227066/

相关文章:

c# - 如何将此方法作为扩展方法添加到我的类的属性中?

c# - 使用 kentico 将用户登录到我的前端网站

c# - 我对接口(interface)感到困惑吗?

c# - 检查运行我的代码需要什么版本的 .NET

c# - 使用 CodeDom 指定类型别名

Dart:无法将类型 'int' 的值分配给类型 'int' 的变量

c# - 在扩展类本身内部使用扩展方法

c# - 我可以在C#中实现从字符串到 bool 值的隐式“转换”吗?

c# - 枚举上的 IEnumerable 扩展方法

c# - MVC 3 - 在我的 'Views' 上创建搜索的最佳方法