Is that possible to add methods to Base classes like List? or others? I really need to add method to generic list class if it has MyClass type. like this: List<MyClass>.FindCoolStuff() or List<MyClass>.SetValueByName()

thanks

有帮助吗?

解决方案

No, but you can use an extension method.

public static class ListExtensions
{
    public static IEnumerable<T> DoCoolStuff<T>(this List<T> collection)
    {
        // Do cool stuff
    }
}

From MSDN: In your code you invoke the extension method with instance method syntax.

var awesomeList = new List<string>();

var awesomestuff = awesomeList.DoCoolStuff();

其他提示

While you cannot add methods to a class, you can give the illusion of doing so using extension methods ( http://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx). Note that these methods will only appear on instances of that class or interface, not on the type (like static methods).

If you want to restrict it to working only for MyClass, you can use the where keyword; so using the example above

public static class ListExtensions
{
    public static IEnumerable<T> DoCoolStuff<T>(this List<T> collection) where T : MyClass
    {
        // Do cool stuff
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top