c# - 使用 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));
解决方案
Activator
仅适用于公共构造函数,具有CreateInstance
您正在使用的简单重载。对于使用private
//构造函数protected
,internal
你需要使用另一个重载。请参阅https://docs.microsoft.com/en-us/dotnet/api/system.activator.createinstance。
推荐阅读
- umbraco7 - 在 Umbraco 7.6 中无法显示自定义部分
- c# - 我的 .Net Core 应用程序如何使用来自另一个应用程序的会话变量?
- flutter - Flutter TextField清除按钮位置错误
- apache-flink - 将 uid 添加到操作员会导致“无法映射操作员的检查点/保存点状态”
- android - Firebase 函数在 10 秒后在客户端提供超时
- javascript - 您如何定位和修改 Ionic/Angular 应用程序中的所有 CSS 元素实例?
- python-3.x - 如何在我的 Python 3 代码中添加异常处理?
- jquery - 将响应属性应用于 true 时,Jquery DataTable 加载数据缓慢
- javascript - 如何在 WebStorm 和 React JSX 中使用 JavaScript 流版本语言?
- javascript - 如何引用javascript json