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

前端 未结 4 1124
眼角桃花
眼角桃花 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 07:49

    class Program
    {
        static void Main(string[] args)
        {
            int s = 38;
    
    
            var t = typeof(Foo);
            var m = t.GetMethod("Bar");
            var g = m.MakeGenericMethod(s.GetType());
            var foo = new Foo();
            g.Invoke(foo, null);
            Console.ReadLine();
        }
    }
    
    public class Foo
    {
        public void Bar()
        {
            Console.WriteLine(typeof(T).ToString());
        }
    }
    

    it works dynamicaly and s can be of any type

提交回复
热议问题