C#如何根据变量名动态地对类的相应成员进行操作
1个回答
展开全部
反射可以用来设置类的私有成员。
using System; using System.Reflection; class Test
{ private int _name; public int GetName() { return _name;
}
} class Program
{ static void Main(string[] args) {
Test t = new Test();
Type tt = t.GetType();
BindingFlags flag = BindingFlags.NonPublic | BindingFlags.Instance;
FieldInfo fieldInfo = tt.GetField("_name", flag);
fieldInfo.SetValue(t, 2);
Console.WriteLine(t.GetName());
}
}
using System; using System.Reflection; class Test
{ private int _name; public int GetName() { return _name;
}
} class Program
{ static void Main(string[] args) {
Test t = new Test();
Type tt = t.GetType();
BindingFlags flag = BindingFlags.NonPublic | BindingFlags.Instance;
FieldInfo fieldInfo = tt.GetField("_name", flag);
fieldInfo.SetValue(t, 2);
Console.WriteLine(t.GetName());
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询