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