3

リフレクションを使用してクラス オブジェクトをリストに追加しようとしていますが、クラス オブジェクトをパラメーターとして 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...
}
4

2 に答える 2

5

List.Add(Processor)呼び出しようとしています-フィールドの値でPC呼び出したい:

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

ただし、個人的には、このようなパブリック フィールドを作成しないことをお勧めします。代わりにプロパティの使用を検討してください。

于 2012-04-05T17:30:36.287 に答える
0

このメソッドはすべてのリストに新しいアイテムを追加します//挿入の代わりに追加を使用します

        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);
于 2014-02-03T04:39:12.787 に答える