首页 > 解决方案 > 使用 Activator 创建实例

问题描述

我在使用 Activator.CreateInstance 时遇到了一些麻烦。它抛出“找不到类型的构造函数”异常。

这是发生错误的方法:

private static void InitializeInternalProperty(Calculation calculation, Type type, IDataProvider dataProvider, params string[] precedants)
{
    PropertiesCollection precedantsCollection = new PropertiesCollection(); //Properties collection implements IKeyedCollection
    foreach (string precedant in precedants)
    {
        precedantsCollection.Add(calculation.properties[precedant]);
    }
    calculation.properties.Add((Property)Activator.CreateInstance(type, dataProvider, precedantsCollection));
}

这是构造函数,我正在尝试使用:

internal CountryRiskPremium(IDataProvider dataProvider, PropertiesCollection precedants)
{
    Name = Names.CountryRiskPremium;
    InitLinks(precedants);
    _dataProvider = dataProvider;
}

我也试过:

object[] arguments = new object[2];
arguments[0] = dataProvider;
arguments[1] = precedantsCollection;
calculation.properties.Add((Property)Activator.CreateInstance(type, arguments));

标签: c#reflection

解决方案


Activator仅适用于公共构造函数,具有CreateInstance您正在使用的简单重载。对于使用private//构造函数protectedinternal你需要使用另一个重载。请参阅https://docs.microsoft.com/en-us/dotnet/api/system.activator.createinstance


推荐阅读