Activator.CreateInstance(T,42,参数)无法找到构造
-
13-09-2019 - |
题
我使用(一个稍微扩展的版本)在工厂图案样式函数以下代码:
public class SingleItemNew : CheckoutContext
{
public BookingContext Data { get; set; }
public SingleItemNew(BookingContext data)
{
Data = data;
}
}
public CheckoutContext findContext(BookingContext data)
{
Type contextType = Type.GetType("CheckoutProcesses." + data.Case.ToString());
CheckoutContext output =
Activator.CreateInstance(contextType, BindingFlags.CreateInstance, new[] { data }) as CheckoutContext;
return output;
}
然而,它将引发constuctor未发现异常时运行,我不能找出原因。
在data.Case.ToString()方法返回一个类,SingleItemNew,即有一个构造采用单个参数的名称。
没有人有任何的想法是什么问题?
干杯编
解决方案
尝试这一个:
Type contextType = Type.GetType("CheckoutProcesses." + data.Case.ToString());
CheckoutContext output =
(CheckoutContext)Activator.CreateInstance(contextType, data);
您的代码不起作用的原因是,Activator.CreateInstance
并没有真正有你想要的过载。所以,你可能想知道为什么代码编译了!原因是,它有一个重载需要哪那么它编译但在运行相匹配的方法调用(Type type, params object[] args)
,它会搜索你的类型的构造采取BindingFlags
和BookingContext[]
这显然不是你喜欢的类型了。
其他提示
时的构造函数public?
时型BookingContext
的单个参数?
麻烦的是,这显然是一个更大的系统的一部分 - 这将是多的更容易帮助你,如果你能产生的这表明该问题短但完整的节目。那么我们就可以修复该程序的问题,你可以端口的修复回你的真实系统。 Otherwisewise我们真的只是猜测:(
SingleItemNew构造是否采取BookingContext作为参数?如果它不匹配exatcly它将失败:
class ParamType { }
class DerivedParamType : ParamType { }
class TypeToCreate
{
public TypeToCreate(DerivedParamType data)
{
// do something
}
}
ParamType args = new ParamType();
// this call will fail: "constructor not found"
object obj = Activator.CreateInstance(typeof(TypeToCreate), new object[] { args });
// this call would work, since the input type matches the constructor
DerivedParamType args = new DerivedParamType();
object obj = Activator.CreateInstance(typeof(TypeToCreate), new object[] { args });
这为我工作。
Type.GetType( “namespace.class,命名空间”);