0

次のような C# コードがあります。

string fieldName = ...
string value = ...

if (fieldName == "a") a = value;
if (fieldName == "b") b = value;
if (fieldName == "c") c = value;
if (fieldName == "d") d = value;
...

私はこのようなものが欲しい:

string fieldName = ...
string value = ...

SetMyInstanceVariable(fieldName, value);
...

それを行う簡単な方法はありますか?文字列でクラスの名前を指定すると、System.Activator を使用してインスタンス化できることを知っています。これは似ているので、期待していました....

4

3 に答える 3

6

ADictionary<string, string>が最も簡単な方法です。

public class Bag {
  var props = new Dictionary<string, string>();

  // ...

  public string this[string key] {
    get { return props[key]; }
    set { props[key] = value; }
  }
}

リフレクション アプローチはかなり複雑ですが、それでも実行可能です。

public class Fruit {
  private int calories = 0;
}

// ...

var f = new Fruit();
Type t = typeof(Fruit);

// Bind to a field named "calories" on the Fruit type.
FieldInfo fi = t.GetField("calories",
  BindingFlags.NonPublic | BindingFlags.Instance);

// Get the value of a field called "calories" on this object.
Console.WriteLine("Field value is: {0}", fi.GetValue(f));

// Set calories to 100. (Warning! Will cause runtime errors if types
// are incompatible -- try using "100" instead of the integer 100, for example.)
fi.SetValue(f, 100);

// Show modified value.
Console.WriteLine("Field value is: {0}", fi.GetValue(f));
于 2010-01-19T05:12:04.950 に答える
4

それらがクラスのプロパティである場合は、次を使用できます。

this.GetType().GetProperty(fieldName).SetValue(this, value, null);

クラス内のフィールド

this.GetType().GetField(fieldName).SetValue(this, value, null);

フィールドのパブリック/プライベート ステータスに基づいてバインディング フラグを変更する必要がある場合があります。

あなたが説明したような関数の単なるローカル変数である場合、私はあなたが運が悪いかもしれないと信じています.

ディクショナリのように、この方法で使用するように設計されたデータ型を使用する方がはるかに望ましいです。おそらく、既存の変数をディクショナリを参照するプロパティに置き換えることを検討する必要があります。例: string a { get { return myDictionary["a"]; } }. これにより、リフレクションに頼ることなく後方互換性を保つことができます。これは本当に最後の手段です。

于 2010-01-19T05:14:37.360 に答える
0

それをすべてに格納するのはどうDictionary<string, string>ですか?

于 2010-01-19T05:04:32.473 に答える