ITPub博客

首页 > 应用开发 > IT综合 > c#反射机制原理

c#反射机制原理

IT综合 作者:wjonne 时间:2015-03-03 14:43:10 0 删除 编辑

.Net Framework 中提供了反射机制,可以再加载程序运行时,动态获取和加载程序集,并且可以获取到程序集的信息

在程序集中,包含模块(Module),模块包含类型,类型包含成员,提供反射,我们可以查看到一个程序集的路径,命名空间,类。我们还可以对其进行操作

可以对程序集的类进行实例化,掉用类中的方法等,就跟我们普通使用程序集一样

反射机制通常有下面一些用途

    • Assembly to define and load assemblies, load modules that are listed in the assembly manifest, and locate a type from this assembly and create an instance of it." style="margin:0px;padding:0px;">使用 Assembly 定义和加载程序集,加载在程序集清单中列出的模块,以及从此程序集中查找类型并创建该类型的实例。

    • Module to discover information such as the assembly that contains the module and the classes in the module." style="margin:0px;padding:0px;">使用 Module 发现以下信息:包含模块的程序集以及模块中的类等。 您还可以获取在模块上定义的所有全局方法或其他特定的非全局方法。

    • ConstructorInfo to discover information such as the name, parameters, access modifiers (such as public or private), and implementation details (such as abstract or virtual) of a constructor." style="margin:0px;padding:0px;">使用 ConstructorInfo 发现以下信息:构造函数的名称、参数、访问修饰符(如 public 或 private)和实现详细信息(如 abstract 或 virtual)等。 GetConstructors or GetConstructor method of a Type to invoke a specific constructor." style="margin:0px;padding:0px;">使用 Type 的 GetConstructors 或 GetConstructor 方法来调用特定的构造函数。

    • MethodInfo to discover information such as the name, return type, parameters, access modifiers (such as public or private), and implementation details (such as abstract or virtual) of a method." style="margin:0px;padding:0px;">使用 MethodInfo 发现以下信息:方法的名称、返回类型、参数、访问修饰符(如 public 或 private)和实现详细信息(如 abstract 或 virtual)等。 GetMethods or GetMethod method of a Type to invoke a specific method." style="margin:0px;padding:0px;">使用 Type 的 GetMethods 或 GetMethod 方法来调用特定的方法。

    • FieldInfo to discover information such as the name, access modifiers (such as public or private) and implementation details (such as static) of a field, and to get or set field values." style="margin:0px;padding:0px;">使用 FieldInfo 发现以下信息:字段的名称、访问修饰符(如 public 或 private)和实现详细信息(如static)等;并获取或设置字段值。

    • EventInfo to discover information such as the name, event-handler data type, custom attributes, declaring type, and reflected type of an event, and to add or remove event handlers." style="margin:0px;padding:0px;">使用 EventInfo 发现以下信息:事件的名称、事件处理程序数据类型、自定义特性、声明类型和反射类型等;并添加或移除事件处理程序。

    • PropertyInfo to discover information such as the name, data type, declaring type, reflected type, and read-only or writable status of a property, and to get or set property values." style="margin:0px;padding:0px;">使用 PropertyInfo 发现以下信息:属性的名称、数据类型、声明类型、反射类型和只读或可写状态等;并获取或设置属性值。

    • ParameterInfo to discover information such as a parameter's name, data type, whether a parameter is an input or output parameter, and the position of the parameter in a method signature." style="margin:0px;padding:0px;">使用 ParameterInfo 发现以下信息:参数的名称、数据类型、参数是输入参数还是输出参数,以及参数在方法签名中的位置等。

    • CustomAttributeData to discover information about custom attributes when you are working in the reflection-only context of an application domain." style="margin:0px;padding:0px;">当您在一个应用程序域的仅反射上下文中工作时,请使用 CustomAttributeData 来发现有关自定义特性的信息。 CustomAttributeData allows you to examine attributes without creating instances of them." style="margin:0px;padding:0px;">通过使用 CustomAttributeData,您不必创建特性的实例就可以检查它们。

关于反射,MSDN上有很详细的说明,这里不详细讲,下面简单说说反射的使用

    http://msdn.microsoft.com/zh-cn/library/windowsphone/develop/f7ykdhsy.aspx

 

1、为了演示,我们自定义一个类库,自定义一个类

复制代码
        namespace 环环环环环
        { public class User
            { //字段 public string Field; //属性 public string Name { get; set; } //构造函数 public User()
                { this.Name = "无参构造";
                } public User(string name)
                { this.Name = name;
                } //public函数 public void PublicShow()
                {
                    Console.WriteLine(string.Format("反射调用一个public方法"));
                } //private函数 private void PrivateShow()
                {
                    Console.WriteLine(string.Format("反射调用一个Private方法"));
                } //static函数 public static string StaticMethod()
                { return "反射调用了一个Static方法";
                } //带参带返回值函数 public string GetString(string name)
                { return string.Format("大家好,我的名字是:{0}!", name);
                } //事件 public event EventHandler eventHandler; //事件处理函数 public void DoEvent()
                { if(eventHandler != null)
                        eventHandler(null, EventArgs.Empty);
                }
            }
        }
复制代码

2、新建一个project,把上面编译好的库 环环环环环.dll 复制到Debug目录下

  加载程序集

复制代码
            //获取程序集  Assembly assembly = Assembly.Load("环环环环环");
            Assembly assembly2 = Assembly.LoadFrom("环环环环环.dll"); //从程序集中获取指定对象类型; Type type = assembly.GetType("环环环环环.User"); //使用Activator创建实例(无参数构造函数) var user1 = Activator.CreateInstance(type); //使用Activator创建实例(带参数构造函数) var user2 = Activator.CreateInstance(type, "薄暮"); //使用Assembly创建实例(无参数构造函数) var user3 = assembly.CreateInstance("环环环环环.User"); //反射无参构造函数 ConstructorInfo constructor1 = type.GetConstructor(new Type[] {}); var user4 = constructor1.Invoke(new object[] { }); //反射有参构造函数  ConstructorInfo constructor2 = type.GetConstructor(new Type[] { typeof(string) }); var user5 = constructor2.Invoke(new object[] { "薄暮" }); //调用public函数(无参数) type.InvokeMember("PublicShow",
                              BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, user1, null); //调用public函数(带参数) string returnValue = type.InvokeMember("GetString",
                                  BindingFlags.InvokeMethod | BindingFlags.OptionalParamBinding, null, user1, new object[] { "薄暮" }) as string; // 调用静态方法  string returnValue2 = type.InvokeMember("StaticMethod", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, new object[] {}) as string; // 调用私有方法 .  type.InvokeMember("PrivateShow",
                              BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, user1, new object[] {}); //反射属性 var Name = type.InvokeMember("Name", BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance, null,
                                  user1, new object[] {}) as string; //设置属性(设置Name属性为"新属性") type.InvokeMember("Name", BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance, null,
                                  user1, new object[] {"新属性"}); //反射字段 string Field = type.InvokeMember("Field", BindingFlags.GetField | BindingFlags.Public | BindingFlags.Instance, null,
                                  user1, new object[] {}) as string; //设置字段(设置Field字段为"新字段") type.InvokeMember("Field", BindingFlags.SetField | BindingFlags.Public | BindingFlags.Instance, null,
                                  user1, new object[] { "新字段" });

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/30105891/viewspace-1446643/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2015-01-15

  • 博文量
    10
  • 访问量
    24620