首先,我們定義一個類:
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; } }
寫一個測試函數:
/// <summary> /// 獲取類的public static/const成員的值 /// </summary> /// <typeparam name="T"></typeparam> public void TestGetValue<T>() { 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<CDynamic>();#endif //Console.WriteLine("sum = {0}, {1}", ret, s); }
完成!
以上這篇利用反射獲得類的public static/const成員的值實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。
新聞熱點
疑難解答
圖片精選