我正在编写一些涉及一些讨厌的反射黑客攻击的代码。目前,我正在创建一个类的实例以及一个 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/