简体   繁体   中英

Specifying dynamic type for generic method

Sorry if this is a duplicate, I've not found what I'm after - everything seems to be talking about ILists.

At the moment I am calling methods and passing the type as a generic which works as you would expect but is causing code duplication. I would like to be able to do

Type.MakeGenericParameter()

But this requires a parameter. I'm calling a generic method, not creating an object. The generic method is not contained with in a generic object.

How can I do something along the lines of

Type desiredType = typeof(IPendingProduct);
...
Product.Save<desiredType>(instance);

Thanks in advance.

typeof(Product).GetMethod("Save").MakeGenericMethod(desiredType)
        .Invoke(null, new object[] {instance});

not nice, huh?

Note this also assumes that Save is public + static, and has no collisions with overloads.

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