C# : Get type parameter at runtime to pass into a

2020-06-08 02:30发布

问题:

The generic Method is...

    public void PrintGeneric2<T>(T test) where T : ITest
    {
        Console.WriteLine("Generic : " + test.myvar);
    }

I'm calling this from Main()...

    Type t = test2.GetType();       
    PrintGeneric2<t>(test2);

I get error "CS0246: the type or namespace name 't' could not be found" and "CS1502: best overloaded method match DoSomethingClass.PrintGeneric2< t >(T) has invalid arguments"

this is related to my previous question here: C# : Passing a Generic Object

I've read that the generic type can't be determined at runtime, without the use of reflection or methodinfo, but I'm not very clear on how to do so in this instance.

Thanks if you can enlighten me =)

回答1:

If you really want to invoke a generic method using a type parameter not known at compile-time, you can write something like:

typeof(YourType)
    .GetMethod("PrintGeneric2")
    .MakeGenericMethod(t)
    .Invoke(instance, new object[] { test2 } );

However, as stated by other responses, Generics might not be the best solution in your case.



回答2:

Generics offer Compile Time parametric polymorphism. You are trying to use them with a type specified only at Runtime. Short answer : it won't work and it has no reason to (except with reflection but that is a different beast altogether).



回答3:

Just call:

PrintGeneric2(test2);

The compiler will infer <t> from what you pass.