繁体   English   中英

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

[英]Activator.CreateInstance failing with 'No parameterless constructor'

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM