Pregunta

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

¿Fue útil?

Solución

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();

Otros consejos

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
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top