简体   繁体   中英

Setting a generic type parameter from a method parameter

Is there any way to do something like this?

void SomeMethod(Type generic)
{
    SomeGenericMethod<generic>();
}

I need to pass the type in as a "normal" parameter and not a generic type parameter.

You can do it with reflection:

public class foo
{
    public void SomeMethod(Type type)
    {
        var methodInfo = this.GetType().GetMethod("SomeGenericMethod");
        var method = methodInfo.MakeGenericMethod(new[] { type });
        method.Invoke(this, null);
    }

    public void SomeGenericMethod<T>()
    {
        Debug.WriteLine(typeof(T).FullName);
    }
}

class Program
{
    static void Main(string[] args)
    {
        var foo = new foo();
        foo.SomeMethod(typeof(string));
        foo.SomeMethod(typeof(foo));
    }
}

That said, using reflection in this way means you are losing some of the benefits of using generics in the first place, so you might want to look at other design alternatives.

Assuming that your method is defined in a class called MyClass, this should do it:

var MyObject = new MyClass();
typeof(MyClass).GetMethod("SomeGenericMethod").MakeGenericMethod(generic).Invoke(myObject, null);

Type.GetMethod() gets an object which describes a method defined in the Type it's called on. The method is generic, so we need to call MakeGenericMethod, and pass its one generic parameter.

We then invoke the method, passing the object we want the method called on and any arguments it takes. As it takes no arguments, we just pass null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM