调用类型参数的方法

Dus*_*san 5 c# generics type-parameter

有没有办法做这样的代码:

class GenericClass<T>
{
    void functionA()
    {
        T.A();
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,如何调用类型参数的函数(类型是我的自定义类).

Mar*_*ell 6

回覆:

T.A();

如果这是你的意思,你不能调用type-parameter的静态方法.你会做的更好重构,作为实例方法T,或许与通用约束(where T : SomeTypeOrInterfaceSomeTypeOrInterface定义A()).另一种选择是dynamic允许对实例方法进行鸭子类型化(通过签名).

如果你的意思是,T只在运行时已知的(作为Type),那么你就需要:

typeof(GenericClass<>).MakeGenericType(type).GetMethod(...).Invoke(...);
Run Code Online (Sandbox Code Playgroud)


Pet*_*ter 2

要调用泛型类型对象的方法,您必须首先实例化它。

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");
    }
}
Run Code Online (Sandbox Code Playgroud)