Activator.CreateInstance失败,返回';没有无参数构造函数';
本文关键字:参数 构造函数 CreateInstance 返回 失败 Activator | 更新日期: 2023-09-27 18:22:38
我正在创建一个方法,该方法将使用CastleWindsor来尝试解析类型,但如果没有配置组件,则使用默认类型(因此在我真正想要更改实现之前,我不必配置所有内容)。这是我的方法。。。
public static T ResolveOrUse<T, U>() where U : T
{
try
{
return container.Resolve<T>();
}
catch (ComponentNotFoundException)
{
try
{
U instance = (U)Activator.CreateInstance(typeof(U).GetType());
return (T)instance;
}
catch(Exception ex)
{
throw new InvalidOperationException("IOC Couldn't instantiate a '" + typeof(U) + "' because: " + ex.Message);
}
}
}
当WebConfigReader作为默认类型传入时,我会得到错误"没有为此对象定义无参数构造函数"。这是我的WebConfigReader类。。。
public class WebConfigReader : IConfigReader
{
public string TfsUri
{
get { return ReadValue<string>("TfsUri"); }
}
private T ReadValue<T>(string configKey)
{
Type type = typeof(T).GetType();
return (T)Convert.ChangeType(ConfigurationManager.AppSettings[configKey], type);
}
}
既然我没有ctor,它应该会起作用。我添加了一个无参数的ctor,并将true作为第二个参数传递给CreateInstance,但上述操作都不起作用。我想不出我错过了什么。有什么想法吗?
typeof(U)
将已经返回U
表示的类型。对其执行额外的GetType()
将返回没有默认构造函数的类型System.Type
。
所以你的第一个代码块可以写成:
public static T ResolveOrUse<T, U>() where U : T
{
try
{
return container.Resolve<T>();
}
catch (ComponentNotFoundException)
{
try
{
U instance = (U)Activator.CreateInstance(typeof(U));
return (T)instance;
}
catch(Exception ex)
{
throw new InvalidOperationException("IOC Couldn't instantiate a '" + typeof(U) + "' because: " + ex.Message);
}
}
}
由于您有一个泛型类型参数,您应该只使用Activator.CreateInstance
的泛型重载
U instance = Activator.CreateInstance<U>();