首先,我们定义一个类:
class CDynamic
{
#if true
public const string TableName = "p_battlerecord"; // OK
//public static string TableName = "p_battlerecord"; // OK
#else
public static string TableName // 用属性不行
{
get { return "hello"; }
}
#endif
public string Name { get; set; }
public int Add(int a, int b)
{
return a + b;
}
}
写一个测试函数:
////// 获取类的public static/const成员的值 /// ///public void TestGetValue () { var tableName = typeof(T).GetField("TableName").GetValue(null); Console.WriteLine(tableName); }
调用测试接口:
public void test1()
{
#if false
var d = new CDynamic(); // 简化演示, 未使用反射
var add = typeof(CDynamic).GetMethod("Add");
var ret = add.Invoke(d, new object[] { 1, 3 });
#else
dynamic d = new CDynamic(); // 使用dynamic动态绑定
var ret = d.Add(1, 3);
//d.Hello(); // 编译通过, 运行将出错(未包含Hello()的定义)
TestGetValue();
#endif
//Console.WriteLine("sum = {0}, {1}", ret, s);
}
完成!
以上这篇利用反射获得类的public static/const成员的值实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持考高分网。



