如何隐藏通过扩展方法的成员方法 [英] How to Hide a member method by an Extension Method

查看:121
本文介绍了如何隐藏通过扩展方法的成员方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 公共静态MyClass类
{
    公共静态无效的添加< T>(名单< T>清单,T项)
    {
        list.Add(项目);
        Console.WriteLine(item.ToString());
    }
}
 

然后

 名单,其中,串>名单=新的名单,其中,串>(){1,2};
list.Add(3);
 

但成员方法将被调用。

反正是有打电话给我扩展方法这样?

我不希望这样称呼它:

  MyClass.Add(列表项)
 

解决方案

您不能。实例方法的总是的采取precedence了扩展方法,假设他们是适用的。会员分辨率将只考虑一旦它没有找到一个非扩展法选项扩展方法。

我建议你只需重命名你的方法 - 除非一点是透明调用此方法与现有的code

如果你做它需要一个的IList< T> 而不是名单,其中,T> ,你可以创建一个它实现包装类型的IList< T> 和代表所有呼叫到包列表,执行任何额外的任务,当您去。然后,您可以的的编写扩展方法的IList< T> 其创建的包装 - 这将允许在某些情况下,更流畅的语法。我个人preFER包装的方法来推导一个新的集合类型,因为它意味着你可以用它与您现有的集合,使得code的变化可能较小......但是这一切都取决于你想要什么做的。

public static class MyClass
{
    public static void Add<T>(this List<T> list, T item)
    {
        list.Add(item);
        Console.WriteLine(item.ToString());
    }
}

then

List<string> list = new List<string>(){"1","2"};
list.Add("3");

But the member method would be called.

Is there anyway to call my Extension Method this way?

I don't want to call it like this:

MyClass.Add(list, item)

解决方案

You can't. Instance methods always take precedence over extension methods, assuming they're applicable. Member resolution will only consider extension methods once it's failed to find a non-extension-method option.

I would suggest you simply rename your method - unless the point was to call this method transparently with existing code.

If you made it take an IList<T> instead of List<T>, you could create a wrapper type which implements IList<T> and delegates all calls onto the wrapped list, performing any extra tasks as you go. You could then also write an extension method to IList<T> which created the wrapper - which would allow for more fluent syntax in some cases. Personally I prefer the wrapper approach to deriving a new collection type, as it means you can use it with your existing collections, making the code changes potentially smaller... but it all depends on what you're trying to do.

这篇关于如何隐藏通过扩展方法的成员方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆