繁体   English   中英

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

[英]C# Reflection Lists: Object does not match target type

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

然后这是 class 的一部分,上面的代码是将 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});

但是,我个人建议您不要拥有这样的公共领域。 考虑改用属性。

此方法会将新项目添加到所有列表//而不是使用 Add 插入

        IList list = (IList)value;// this what you need to do convert ur parameter value to ilist

        if (value == null)
        {
            return;//or throw an excpetion
        }

        Type magicType = value.GetType().GetGenericArguments()[0];//Get class type of list
        ConstructorInfo magicConstructor = magicType.GetConstructor(Type.EmptyTypes);//Get constructor reference

        if (magicConstructor == null)
        {
            throw new InvalidOperationException(string.Format("Object {0} does not have a default constructor defined", magicType.Name.ToString()));
        }

        object magicClassObject = magicConstructor.Invoke(new object[] { });//Create new instance
        if (magicClassObject == null)
        {
            throw new ArgumentNullException(string.Format("Class {0} cannot be null.", magicType.Name.ToString()));
        }
        list.Insert(0, magicClassObject);
        list.Add(magicClassObject);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM