Activator.CreateInstance失败并显示'No parameterless constructor'

son*_*lis 2 c#

我正在创建一个方法,它将使用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);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

当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);
    }
}
Run Code Online (Sandbox Code Playgroud)

由于我没有ctor,它应该工作.我添加了一个无用的ctor,我已经传入了true作为CreateInstance的第二个参数,并且没有上述工作.我无法弄清楚我错过了什么.有什么想法吗?

M.B*_*ock 10

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 同样的错误也出现在`ReadValue <T>()`方法中 - 只需使用`typeof(U)` (3认同)

Jar*_*Par 5

由于您有一个泛型类型参数,您应该只使用泛型重载 Activator.CreateInstance

U instance = Activator.CreateInstance<U>();
Run Code Online (Sandbox Code Playgroud)