简体   繁体   中英

Call a method of type parameter

Is there any way to do code such this:

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

Or, how to call a function of type parameter (type is some my custom class).

Re:

TA();

You can't call static methods of the type-parameter, if that is what you mean. You would do better to refactor that as an instance method of T , perhaps with a generic constraint ( where T : SomeTypeOrInterface , with SomeTypeOrInterface defining A() ). Another alternative is dynamic , which allows duck-typing of instance methods (via signature).

If you mean that the T is only known at runtime (as a Type ), then you would need:

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

I think you are looking for generic type constraints :

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

In terms of the code you posted - in order to call something on T , you will need to pass it as a parameter to functionA . The constraint you use will have to ensure that any T has an A method that can be used.

To call a method of a generic type object you have to instantiate it first.

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");
    }
}

I understand from your code that you want to call a type parameter static method, and that's just impossible.

See here for more info : Calling a static method on a generic type parameter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM