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

时间:2012-02-05 02:39:57

标签: 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);
            }
        }
    }

当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的第二个参数,并且没有上述工作。我无法弄清楚我错过了什么。有什么想法吗?

2 个答案:

答案 0 :(得分:9)

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);
        }
    }
}

答案 1 :(得分:4)

由于您具有泛型类型参数,因此您应该使用Activator.CreateInstance

的泛型重载
U instance = Activator.CreateInstance<U>();
相关问题