Reflection is used to obtain a value instance of the public static and const member of the class

  • 2020-05-10 18:36:40
  • OfStack

First, we define a class:


class CDynamic
 {
#if true
 public const string TableName = "p_battlerecord"; // OK
 //public static string TableName = "p_battlerecord"; // OK
#else
 public static string TableName   //  You can't use attributes 
 {
  get { return "hello"; }
 }
#endif

 public string Name { get; set; }

 public int Add(int a, int b)
 {
  return a + b;
 }
 }

Write 1 test function:


 /// <summary>
 ///  For class public static/const Members of the value of the 
 /// </summary>
 /// <typeparam name="T"></typeparam>
 public void TestGetValue<T>()
 {
  var tableName = typeof(T).GetField("TableName").GetValue(null);
  Console.WriteLine(tableName);
 }

Call test interface:


public void test1()
 {
#if false
  var d = new CDynamic();    //  Simplify the presentation ,  Unused reflection 
  var add = typeof(CDynamic).GetMethod("Add");
  var ret = add.Invoke(d, new object[] { 1, 3 });
#else
  dynamic d = new CDynamic();    //  use dynamic Dynamic binding 
  var ret = d.Add(1, 3);
  //d.Hello();      //  Compiled by ,  Running will go wrong ( Not contain Hello() The definition of )

  TestGetValue<CDynamic>();
#endif

  //Console.WriteLine("sum = {0}, {1}", ret, s);
 }

Done!


Related articles: