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

前端 未结 4 1119
眼角桃花
眼角桃花 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<T>()
        {
            Console.WriteLine(typeof(T).ToString());
        }
    }
    

    it works dynamicaly and s can be of any type

    0 讨论(0)
  • 2020-12-14 07:51

    A few years late and from a msdn blog, but this might help:

    Type t = typeof(Customer);  
    IList list = (IList)Activator.CreateInstance((typeof(List<>).MakeGenericType(t)));  
    Console.WriteLine(list.GetType().FullName); 
    
    0 讨论(0)
  • 2020-12-14 07:59

    I solved this problem in a different way. I have a list class that encapsulates the (real) Dapper functionality. It inherits from a base class that is the dummy class for mocking. Every method in the base class is overridden by the real class. Then I don't need to do anything special. If in the future, I want to do something special with SQLite or a home-grown in-memory database, I can always add that to the base class later if I wish.

    0 讨论(0)
  • 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>(T instance)
        {
            Console.WriteLine("called " + instance);
        }
    }
    

    MakeGenericMethod.

    0 讨论(0)
提交回复
热议问题