How do I use typeof or GetType () as a general pattern?

If it's harder to explain the use of words, take a look at an example I have a generic function like this

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

      

If I have a reflected type, how do I use it with the specified function? I am looking forward to it.

Type a = Type.GetType("System.Windows.Forms.Form");
FunctionA<a>();

      

Because of this, the above method does not work.

+23


source to share


4 answers


You can not. Generics in .NET must be resolved at compile time. You are trying to do something that will resolve them at runtime.

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




Hmmm ... the commentator 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 .

+13


source


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 dynamically and can be of any type

+11


source


A few years later and from the MSDN blog, but this might help:

Type t = typeof(Customer);  
IList list = (IList)Activator.CreateInstance((typeof(List<>).MakeGenericType(t)));  
Console.WriteLine(list.GetType().FullName); 

      

+7


source


I solved this problem in a different way. I have a list of a class that encapsulates the (real) functionality of Dapper. It inherits from the base class, which is a dummy mock class. Every method in the base class is overridden by the real class. Then I don't have to do anything special. If in the future I want to do something special with SQLite

or my own in-memory database, I can always add this to the base class later if I want.

0


source







All Articles