【问题标题】:Extension Methods on both IList and IEnumerable with the same name?IList 和 IEnumerable 上同名的扩展方法?
【发布时间】:2011-01-01 09:44:42
【问题描述】:

我已经编写了some extension Methods 来将 IEnumerable 和 IList 转换为字符串。现在,由于 IList 继承自 IEnumerable,因此我必须对它们进行不同的命名。

我只是想知道是否有办法避免这种情况? 我可以在 IEnumerable 上使用扩展方法,然后在 IList 上使用具有相同名称​​和相同签名的不同方法吗?有点像覆盖,除了扩展方法当然是静态的。

我只想在 List 上使用更有效的方法体,而不必有第二个方法名称。

是的,我知道在这种特定情况下,我应该首先运行分析器以真正查看第二种方法是否更好,但我很感兴趣是否通常可以覆盖派生类中的扩展方法。

【问题讨论】:

    标签: c# .net extension-methods


    【解决方案1】:

    你为什么不做 BCL 所做的事情,并在同一个方法中尝试向下转换?

    类似这样的:

    public static string Foo<T>(this IEnumerable<T> source)
    {
        var list = source as IList<T>;
        if(list != null)
        {
            // use more efficient algorithm and return
        }
        // default to basic algorithm
    }
    

    如果您绝对必须拥有两个具有相同名称的独立扩展方法,则可以将它们放在两个不同命名空间的类中,但这意味着您永远不能在同一代码中同时使用它们文件,所以这几乎不是最优的。

    【讨论】:

    • 有趣的方法,可行 - 你知道 BCL 是在哪里做的吗?
    • Enumerable.Count() 这样做 - 它检查 ICollection&lt;T&gt; 并使用 .Count 作为快捷方式。
    【解决方案2】:

    Daniel Cazzulino 最近发表了一篇关于模拟扩展方法的博文,并在博文中描述了他的方法,该方法不仅将类似命名空间的分组应用于相关的扩展方法,而且还描​​述了如何从本质上实现扩展属性。 em> Here's the blog post. 内心充满了敬畏。

    本质上,您将相关方法封装在一个对象中,并从扩展方法返回一个实例:

    public interface ISecurity
    {
        Permissions GetPermissions(Uri resource);
    }
    
    public static class SecurityExtensions
    {
        public static ISecurity Security(this IPerson person)
        {
           return new SecurityImpl(person);
        }
    }
    

    您可以使用这种技术来“命名空间”您的扩展方法。

    【讨论】:

      猜你喜欢
      • 2015-04-01
      • 2013-06-24
      • 2019-03-17
      • 2010-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-06
      • 2012-01-16
      相关资源
      最近更新 更多