代码改变世界

反射的简单应用

2016-02-04 10:16  糯米粥  阅读(365)  评论(0编辑  收藏  举报

首先有一个类

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace ConsoleApplication1
 8 {
 9     public class demo
10     {
11         public string name = "程序员";
12     }
13 }

测试类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{

    class Program
    {
        static void Main(string[] args)
        {

            Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            Type type = assembly.GetType("ConsoleApplication1.demo");     //命名空间名 + 类名
            object obj = Activator.CreateInstance(type, true);

            FieldInfo classField = type.GetField("name");
            string name = classField.GetValue(obj).ToString();
            Console.WriteLine(name);

        }
    }
}

运行后发现已经获取得到值了

 

因为Activator.CreateInstance是创建一个新实例。

 

但只想想想。这个name的值是固定的。也就是在项目中需要动态赋值

然后动态反射出来。即反射获取当前实例的值

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Reflection;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 
 8 namespace ConsoleApplication1
 9 {
10 
11     class Program
12     {
13         static void Main(string[] args)
14         {
15 
16             //创建一个实例
17             demo d = new demo();
18             d.name = "开发工程师";
19 
20             FieldInfo field = d.GetType().GetField("name");//获取类中的一个Field
21             object fieldValue = field.GetValue(d);//获取这个实例中的Field的代表的属性
22 
23             //Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
24             //Type type = assembly.GetType("ConsoleApplication1.demo");     //命名空间名 + 类名
25             //object obj = Activator.CreateInstance(type, true);
26 
27             //FieldInfo classField = type.GetField("name");
28             //string name = classField.GetValue(obj).ToString();
29             Console.WriteLine(fieldValue);
30 
31         }
32     }
33 }

结果是正确的。

 

博客园有很多前辈写的

http://www.cnblogs.com/davidyang78/archive/2010/06/09/1754562.html

http://www.cnblogs.com/zhangpengshou/archive/2012/03/21/2409206.html