在C#中按名称(字符串)访问实例变量,就像动态语言一样 [英] Accessing an instance variable by name (string), kinda like dynamic languages do, in C#

查看:57
本文介绍了在C#中按名称(字符串)访问实例变量,就像动态语言一样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些这样的C#代码:

i've got some C# code like this:

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实例化它,这有点相似,所以我希望....

Is there a simple way to do it? I know that given a class's name in a string, you can instantiate it with System.Activator, and this is kindof similar so i was hoping....

推荐答案

Dictionary< string,string> 是最简单的方法:

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

  // ...

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

反射方法要复杂得多,但仍然可行:

The reflection approach is considerably more complex but still doable:

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));

这篇关于在C#中按名称(字符串)访问实例变量,就像动态语言一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆