C# 用字符串作为变量名

.

.

.

.

如果使用string变量中的字符串作为另一个变量的名字,需要通过反射取得字符串对象,可以通过如下方式实现:

View Code
1 BindingFlags bf = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static;
2 Type type = this.GetType();
3 FieldInfo fi = type.GetField("变量名的字符串", bf);
4 string sql = fi.GetValue(this).ToString();

 

也可以写成另外一种形式:

View Code
1 BindingFlags bf = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static;
2 string sql = this.GetType().GetField("变量名的字符串", bf).GetValue(this).ToString();



posted on 2011-11-04 18:12  0xCAFEBABE  阅读(3318)  评论(0编辑  收藏  举报

导航