How to use typeof or GetType() as Generic's Template?

前端 未结 4 1120
眼角桃花
眼角桃花 2020-12-14 06:57

If it\'s harder to explain using words, let\'s look at an example I have a generic function like this

void FunctionA() where T : Form, new()
{
}
         


        
4条回答
  •  南方客
    南方客 (楼主)
    2020-12-14 08:02

    You can't. Generics in .NET must be resolved at compile time. You're trying to do something that would resolve them at runtime.

    The only thing you can do is to provide an overload for FunctionA that takes a type object.


    Hmmm... the commenter is right.

    class Program
    {
        static void Main(string[] args)
        {
            var t = typeof(Foo);
            var m = t.GetMethod("Bar");
            var hurr = m.MakeGenericMethod(typeof(string));
            var foo = new Foo();
            hurr.Invoke(foo, new string[]{"lol"});
            Console.ReadLine();
        }
    }
    
    public class Foo
    {
        public void Bar(T instance)
        {
            Console.WriteLine("called " + instance);
        }
    }
    

    MakeGenericMethod.

提交回复
热议问题