Call the type parameter method

Is there any way to make this code:

class GenericClass<T>
{
    void functionA()
    {
        T.A();
    }
}

Or how to call the type parameter function (type is my own class).

+5
source share
4 answers

To call an object method of a generic type, you must first create it.

public static void RunSnippet()
{
    var c = new GenericClass<SomeType>();
}

public class GenericClass<T> where T : SomeType, new()
{
    public GenericClass(){
        (new T()).functionA();
    }   
}

public class SomeType
{
    public void functionA()
    {
        //do something here
        Console.WriteLine("I wrote this");
    }
}
+2
source

Re:

T.A();

You cannot call static methods of a type parameter if that is what you mean. You would be better off reorganizing this as an instance method T, perhaps with a common constraint ( where T : SomeTypeOrInterface, with SomeTypeOrInterface, defining A()). Another alternative is dynamicthat allows duck typing of instance methods (via signature).

, T ( Type), :

typeof(GenericClass<>).MakeGenericType(type).GetMethod(...).Invoke(...);
+6

, :

class GenericClass<T> where T : MyBaseClass
{
    void functionA<T>(T something)
    {
        something.A();
    }
}

, , - T, functionA. , , , T A, .

+2

, , .

. :

+1

All Articles