c# - 无法将通过反射创建的类添加到容器中

标签 c# reflection

我正在编写一些涉及一些讨厌的反射黑客攻击的代码。目前,我正在创建一个类的实例以及一个 List<T>该类的容器,其中使用的类由字符串确定。目前所有内容都包含在同一个程序集中。

Type containerType = typeof(List<>);

Assembly currentAsm = Assembly.GetExecutingAssembly();
Type applicationModelType = currentAsm.GetType("NamespaceName." + targetApplicationModel);

Type applicationModelContainerType = containerType.MakeGenericType(applicationModelType);
dynamic container = Activator.CreateInstance(applicationModelContainerType);

在这种情况下 targetApplicationModel是一个字符串,其中包含用于列表的对象和通用部分的类的名称。现在我想创建一个该类型的实例并将其添加到容器中:

var x = Activator.CreateInstance(applicationModelType);
container.Add(y);
var y = container.Item[0];

然而调用Add失败

Exception thrown: 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' in System.Core.dll
An unhandled exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll
The best overloaded method match for 'System.Collections.Generic.List<MyType>.Add(MyType)' has some invalid arguments

通过在调试时检查 x,我可以非常确定确实是 MyType 的一个实例所以我不知道为什么调用失败。

最佳答案

跟进我的“不要使用dynamic”评论。我做了以下事情:

首先我创建了一个虚拟类:

public class ClassToCollect
{
    public string SomeProperty { get; set; } = "Hello World";
}

然后我运行了这段代码:

var containerType = typeof(List<>);
var itemType = typeof(ClassToCollect);
var fullContainerType = containerType.MakeGenericType(itemType);
var container = Activator.CreateInstance(fullContainerType);
var addMethod = fullContainerType.GetMethod("Add");
var objectToAdd = Activator.CreateInstance(itemType);
addMethod.Invoke(container, new object[] { objectToAdd });

在该代码的末尾,我可以看到列表中的一项。

关于c# - 无法将通过反射创建的类添加到容器中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69104809/

相关文章:

c# - 通过缓存或委托(delegate)调用提高性能?

c# - 如何使用 HTMLTextWriter 创建间距和缩进?

c# - 在 CPU 密集型计算中需要 Blazor Wasm 性能改进

c# - xUnit 测试引擎的 InlineDataAttribute + 可选方法参数

.net - 如何通过类型名称获取泛型接口(interface)的类型?

java - field.setAccessible(false) 对非私有(private)字段的影响

非静态字段、方法或属性需要 C# 对象引用 'Assignment_1.frmMain.setListIndex(int)'

c# - 如何在窗口的特定位置绘制像素?

c# - 在使用默认方法实现接口(interface)的类上使用 `GetMethod` 返回 null

c# - 如何确定数组的基础类型