我和Activator.CreateInstance有一些麻烦。它抛出"Constructor on type not“异常。
以下是发生错误的方法:
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));发布于 2020-02-18 11:09:32
Activator只适用于公共构造函数,只使用您正在使用的CreateInstance的简单重载。对于使用private/protected/internal构造函数,需要使用另一个重载。见https://learn.microsoft.com/en-us/dotnet/api/system.activator.createinstance。
https://stackoverflow.com/questions/60279478
复制相似问题