2024年4月20日发(作者:)

C#反射机制

最近仔细学习了一下C#的反射机制,希望能和大家分享。 提到反射我想大家都不陌生,反射

提供了封装程序集、模块和类型的对象( Type 类型)。可以使用反射动态创建类型的实例,

将类型绑定到现有对象,或从现有对象获取类型并调用其方法或访问其字段和属性,所在命名

空间using tion。

反射的作用:

1.使用反射可以动态创建类型的实例,然后将实例再邦定到现有的对象或从现有对象中获取类

型。

2.应用程序需要在运行时从某个特定的程序集中载入特定的类型,以创建特定类型的实例。

3. 正是因为反射的特性(动态创建实例)所以在多个模块之间减少代码的紧偶合方面,利用

反射可以起到了很大的改善。但是反射也有它的弊端,就是要以牺牲性能为代价,而且有些信

息利用反射是无法得到的。在使用时要根据情况进行选择。我想通过下图的层次模型大家可能

会更明白它的机制。

以上关于反射知识了解之后,在通过代码大家可能会更好的理解反射:

首先在Vs2008中创建一个类型,命名为ReflectDemo类库。并添加一个名为ReflectTest

的类

using System;

using c;

using ;

using ;

namespace tDemo

{

public class ReflectTest : IPerson

{

private string _name;

private int _age;

public string Name { get { return this._name; } set { this._name =

value; } }

public int Age { get { return this._age; } set { this._age = value; } }

public ReflectTest(string name, int age)

{

this._name = name;

this._age = age;

}

public string WelcomeInfo(string name)

{

return "welcome come here " + name;

}

public static string WriteStaticInfo(string name)

{

return "welcome come here static" + name;

}

public static string WriteStaticNoParam()

{

return "Static and No parma";