[英]How can I get a constructor for a type when one of the parameters is dynamic?
I have a series of classes with this constructor: 我的构造函数有一系列的类:
MyClass(Reader reader, dynamic json) { ... }
I need to instantiate objects in a generic method. 我需要在通用方法中实例化对象。 To do so I tried to get the constructor thuswise: 为此,我尝试以此方式获取构造函数:
class Reader
...
T Get<T>(string id)
{
dynamic json = GetData(id);
var constructor = typeof(T).GetConstructor(new Type[] { typeof(Reader), typeof(dynamic) });
return constructor.Invoke(new object[] { this, json });
}
However, neither dynamic
nor typeof(dynamic)
is acceptable in this circumstance. 但是,在这种情况下, dynamic
和typeof(dynamic)
都不可接受。 What's the appropriate way to do so? 这样做的合适方法是什么? The constructor certainly does exist. 构造函数确实存在。 There does not seem to be a binding flag for this situation. 对于这种情况似乎没有绑定标志。
For the moment, I've created a dead-simple JsonWrapper
class as a workaround: 目前,我已经创建了一个简单的JsonWrapper
类作为解决方法:
class JsonWrapper
{
JsonWrapper(dynamic json) { Json = json; }
dynamic Json { get; private set; }
}
...
var constructor = typeof(T).GetConstructor(new Type[] { typeof(Reader), typeof(JsonWrapper) });
I could also call GetConstructors()
and take the first entry, as these classes only have the one - but that would be fragile. 我也可以调用GetConstructors()
并获取第一个条目,因为这些类只有一个-但这很脆弱。
However, neither
dynamic
nortypeof(dynamic)
is acceptable in this circumstance. 但是,在这种情况下,dynamic
和typeof(dynamic)
都不可接受。
Consider using typeof(object)
instead of typeof(dynamic)
. 考虑使用typeof(object)
而不是typeof(dynamic)
。
MSDN says about dynamic
that MSDN说dynamic
In most cases, it functions like it has type object. 在大多数情况下,它的功能就像具有类型对象。
In particular, the following code fails with error "Type '....JsonWrapper' already defines a member called 'JsonWrapper' with the same parameter types" 特别是,以下代码失败,并显示错误“类型'.... JsonWrapper'已经定义了具有相同参数类型的成员'JsonWrapper'”
public class JsonWrapper
{
public JsonWrapper(dynamic json) { }
public JsonWrapper(object json) { }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.