C#Question .Netバージョン4.6.1C#クラスからフィールドの参照を取得し、参照を使用してメソッドを呼び出す方法はありますか?
私は以下のようなクラスを持っていますが、私はそのクラスのインスタンスを作成します。私は、クラスインスタンスからのフィールドへの参照を作成し、クラス変数 "Name"と "Description"にメソッド "Insert"を呼びたいと思います。
Google検索で「C#での の反映を介してクラスフィールドへの参照を取得する」を使用しました。私は反射のためにstackoverflowに関する情報を見つけましたが、メソッドの呼び出しについては言及していません。私はそれを使ってポインタのようなものを見つけることができました。しかし、私は参考にメソッドを呼び出すすべての方法を作ることができませんでした。私は間違った質問をGoogleに求めているか、私がしようとしていることは不可能です。
C# Reflection - Get field values from a simple class
Class AClass1
{
public String Action = String.Empty;
public List<KeyValuePair<String, String>> Description = new List<KeyValuePair<string, string>>();
public List<KeyValuePair<String, String>> Name= new List<KeyValuePair<string, string>>();
}
// Psudo code:
// The code has been reduced down to show the problem. Error handling
// etc has been removed. This may not compile because I had to
// reduce down the code to show what I am trying to accomplish. Any
// suggestions for creating a reference to a class variable and calling
// its methods would be appreciated. If needed I can create a small
// sample that does compile but I think the sample provided shows
// what I am trying to accomplish. If not let me know and I will
// scale down further.
public void ProcessFeature1(String fieldName, String value1, String value2)
{
AClass1 featureToManage = new AClass1();
KeyValuePair<string, string> entry = new KeyValuePair<string, string>(value1, value2);
if (entry != null)
{
// something along these lines is preferred if possible
var ptrField = featureToManage.GetType().GetField(fieldName).FieldHandle;
if (ptrField != null)
{
// the problem is figuring how to turn the value from reflection into
// something I can call directly. I have tried casting to the same
// type as the variable in the class (not shown here)
// but it did not work or I did it wrong. When I say it does not
// work the run-time information does not show the method and the
// compiler complains generally saying no such method Insert found.
ptrField.Insert(0, entry);
}
else
{
// this works but would prefer to lookup the
// the field in the class and call methods so I
// 1. have less code
// 2. do not have to hard code the name of the field.
switch (fieldName)
{
case "Name":
{
featureToManage.Name.Insert(0, entry);
break;
}
case "Description":
{
featureToManage.Description.Insert(0, entry);
break;
}
default:
{
// something bad happened
break;
}
}
}
}
}