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 回答