简体   繁体   English

为泛型方法指定动态类型

[英]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. 抱歉,如果重复的话,我还没找到我想要的东西-似乎所有事情都在谈论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. 注意,这还假设Save是public + static,并且与重载没有冲突。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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