哪个Activator.CreateInstance重载函数可以调用?

时间:2010-03-24 20:17:50

标签: c#-3.0

调用哪个Activator.CreateInstance重载函数?我有一个返回的类型 “输入proxyType = GetProxyType(contractType);”而constructorinfo是

“[System.Reflection.RuntimeConstructorInfo] = {Void .ctor(System.ServiceModel.InstanceContext)} base {System.Reflection.MemberInfo} = {Void .ctor(System.ServiceModel.InstanceContext)}

[System.Reflection.RuntimeConstructorInfo] = {Void .ctor(System.ServiceModel.InstanceContext,System.String)} base {System.Reflection.MethodBase} = {Void .ctor(System.ServiceModel.InstanceContext,System.String)}

[System.Reflection.RuntimeConstructorInfo] = {Void .ctor(System.ServiceModel.InstanceContext,System.String,System.String)} base {System.Reflection.MethodBase} = {Void .ctor(System.ServiceModel.InstanceContext,System.String,System.String)}

[System.Reflection.RuntimeConstructorInfo] = {Void .ctor(System.ServiceModel.InstanceContext,System.String,System.ServiceModel.EndpointAddress)} base {System.Reflection.MethodBase} = {Void .ctor(System.ServiceModel.InstanceContext,System.String,System.ServiceModel.EndpointAddress)}

[System.Reflection.RuntimeConstructorInfo] = {Void .ctor(System.ServiceModel.InstanceContext,System.ServiceModel.Channels.Binding,System.ServiceModel.EndpointAddress)} base {System.Reflection.MethodBase} = {Void .ctor(System.ServiceModel.InstanceContext,System.ServiceModel.Channels.Binding,System.ServiceModel.EndpointAddress)}。

谢谢!

1 个答案:

答案 0 :(得分:0)

似乎该类型具有默认构造函数,因此Activator.CreateInstance(proxyType);应该有效。如果你想调用一些其他构造函数,例如带有字符串参数的构造函数,你可以这样做:

var instance = Activator.CreateInstance(proxyType, "some string parameter");

或带有两个字符串参数的那个:

var instance = Activator.CreateInstance(proxyType, "param1", "param2");

更新:

我的错误是没有定义此类型的无参数构造函数。所有构造函数都需要至少一个类型为InstanceContext的参数。因此,为了创建此类型的实例,您至少需要传递实例上下文。例如,如果您在WCF中,可以尝试这样做:

var instance = Activator.CreateInstance(
    proxyType, 
    OperationContext.Current.InstanceContext
);