C#反射列表:对象与目标类型不匹配

CJx*_*JxD 3 c# reflection

尝试使用反射将类对象添加到列表中,但是以类对象作为参数调用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});
Run Code Online (Sandbox Code Playgroud)

然后这是该类的一部分,上面的代码将classContainers添加到:

public class PC
{
    public List<Processor> Processor = new List<Processor>();
    public List<Motherboard> Motherboard = new List<Motherboard>();
    // Etc...
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

你想呼叫List.Add(Processor)PC-你怎么称呼它在该领域的价值

field.FieldType.GetMethod("Add").Invoke(field.GetValue(fetched),
                                        new[] {classContainer});
Run Code Online (Sandbox Code Playgroud)

但是,我个人建议您不要使用此类公共领域。考虑改用属性。