How to Hide a member method by an Extension Method
public static class MyClass
{
public static void Add<T>(this List<T> list, T item)
{
lis开发者_Go百科t.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.
Instance methods always take precedence over extension methods, so no.
The correct thing to do here would appear to be polymorphism - but note that List<T>
doesn't provide virtual
methods. Collection<T>
does, though:
using System;
using System.Collections.ObjectModel;
class MyClass<T> : Collection<T> {
protected override void InsertItem(int index, T item) {
base.InsertItem(index, item);
Console.WriteLine("Added:" + item.ToString());
}
protected override void SetItem(int index, T item) {
base.SetItem(index, item);
Console.WriteLine("Set (indexer):" + item.ToString());
}
// see also ClearItems and RemoveItem
}
精彩评论