C# 反射,使用 MakeGenericMethod 和具有“new()”的方法;类型约束
我正在尝试按如下方式使用 MethodInfo MakeGenericMethod:
foreach (var type in types)
{
object output = null;
var method = typeof (ContentTypeResolver).GetMethod("TryConstruct");
var genmethod = method.MakeGenericMethod(type);
var arr = new object[] { from, output };
if ((bool)genmethod.Invoke(null, arr))
return (IThingy)arr[1];
}
针对以下通用方法:
public static bool TryConstruct<T>(string from, out IThingy result) where T : IThingy, new()
{
var thing = new T();
return thingTryConstructFrom(from, out result);
}
我遇到的问题是,我在 MakeGenericMethod 行上遇到争论异常,因为我传递的类型不是“new()”
是否有解决方法这?? 谢谢
I am trying to use the MethodInfo MakeGenericMethod as follows:
foreach (var type in types)
{
object output = null;
var method = typeof (ContentTypeResolver).GetMethod("TryConstruct");
var genmethod = method.MakeGenericMethod(type);
var arr = new object[] { from, output };
if ((bool)genmethod.Invoke(null, arr))
return (IThingy)arr[1];
}
Against the following generic method:
public static bool TryConstruct<T>(string from, out IThingy result) where T : IThingy, new()
{
var thing = new T();
return thingTryConstructFrom(from, out result);
}
The problem I having is that I get an arguement exception on the MakeGenericMethod line as the type I am passing is not 'new()'
Is there a way round this??
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不可以。您只能使用满足
ITingy
和new
约束的类型参数来创建封闭构造的 TryConstruct 方法。否则你就会破坏 TryConstruct 合约:当你调用 TryConstruct 并且它到达new T()
行时会发生什么?不会有 T() 构造函数,因此违反了类型安全。在将类型传递给 MakeGenericMethod 之前,您需要检查该类型是否具有公共默认构造函数。如果您需要使用非默认构造函数实例化类型,则需要创建一个新方法或 TryConstruct 重载,可能使用 Activator.CreateInstance 而不是
new T()
。No. You can only make closed constructed TryConstruct methods with type parameters that meet the
IThingy
andnew
constraints. Otherwise you'd be defeating the TryConstruct contract: what would happen when you called TryConstruct and it hit thenew T()
line? There wouldn't be a T() constructor, so you'd have violated type safety.You need to check that type has a public default constructor before passing it to MakeGenericMethod. If you need to instantiate types with a nondefault constructor, you need to create a new method or a TryConstruct overload, perhaps one which uses Activator.CreateInstance instead of
new T()
.