如何隐藏通过扩展方法的成员方法方法、成员

2023-09-04 23:49:00 作者:野爹

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

然后

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

但成员方法将被调用。

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

我不希望这样称呼它:

  MyClass.Add(列表项)
 
kotlin学习第二天 类,扩展方法,高阶函数初步学习

解决方案

您不能。实例方法的总是的采取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.