gpt4 book ai didi

C# 反射列表 : Object does not match target type

转载 作者:行者123 更新时间:2023-11-30 15:04:37 25 4
gpt4 key购买 nike

尝试使用反射将类对象添加到列表中,但是当使用我的类对象作为参数调用 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...
}

最佳答案

您正在尝试在 PC 上调用 List.Add(Processor) - 您希望在字段的值上调用它 :

field.FieldType.GetMethod("Add").Invoke(field.GetValue(fetched),
new[] {classContainer});

但是,我个人建议您不要拥有这样的公共(public)字段。考虑改用属性。

关于C# 反射列表 : Object does not match target type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10033141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com