尝试使用反射将一个类对象添加到列表中,但是当用我的类对象作为参数调用Add方法时,我得到了“对象不符合目标类型”的错误。
以下是相关的代码片段(您可以暂时假设classString = “Processor”
):
PC fetched = new PC();
// Get the appropriate computer field to write to
FieldInfo field = fetched.GetType().GetField(classString);
// Prepare a container by making a new instance of the reffered class
// "CoreView" is the namespace of the program.
object classContainer = Activator.CreateInstance(Type.GetType("CoreView." + classString));
/*
classContainer population code
*/
// This is where I get the error. I know that classContainer is definitely
// the correct type for the list it's being added to at this point.
field.FieldType.GetMethod("Add").Invoke(fetched, new[] {classContainer});
那么上述代码正在向以下类添加 classContainers:
public class PC
{
public List<Processor> Processor = new List<Processor>();
public List<Motherboard> Motherboard = new List<Motherboard>();
// Etc...
}