WEB开发网
开发学院软件开发C语言 C#反射概念以及实例详解 阅读

C#反射概念以及实例详解

 2010-09-30 20:51:41 来源:WEB开发网   
核心提示:C#反射的入门学习首先要明白C#反射提供了封装程序集、模块和类型的对象等等,那么这样可以使用反射动态创建类型的实例,C#反射概念以及实例详解,将类型绑定到现有对象,或从现有对象获取类型并调用其方法或访问其字段和属性,一个最简单的C#反射实例,首先编写类库如下:usingSystem;namespaceReflectio

C#反射的入门学习首先要明白C#反射提供了封装程序集、模块和类型的对象等等。那么这样可以使用反射动态创建类型的实例,将类型绑定到现有对象,或从现有对象获取类型并调用其方法或访问其字段和属性。如果代码中使用了属性,可以利用反射对它们进行访问。

一个最简单的C#反射实例,首先编写类库如下:

using System;  
 
namespace ReflectionTest  
{  
public class WriteTest  
{  
//public method with parametors  
public void WriteString(string s, int i)  
{  
Console.WriteLine("WriteString:" + s + i.ToString());  
}  
 
//static method with only one parametor  
public static void StaticWriteString(string s)  
{  
Console.WriteLine("StaticWriteString:" + s);  
}  
 
//static method with no parametor  
public static void NoneParaWriteString()  
{  
Console.WriteLine("NoParaWriteString");  
}  
}  
} 

使用命令行编译csc /t:library ReflectTest.cs命令进行编译,生成ReflectTest.dll库文件。

然后进行下列程序的编写:

using System;  
using System.Reflection;  
 
class TestApp  
{  
public static void Main()  
{  
Assembly ass;  
Type type;  
Object obj;  
 
//Used to test the static method  
Object any = new Object();  
 
//Load the dll  
//Must indicates the whole path of dll  
ass = Assembly.LoadFile(@"D:\Source Code\00.C#   
Sudy\01.Reflection\01\ReflectTest.dll");   
//Must be Namespace with class name  
type = ass.GetType("ReflectionTest.WriteTest");  
 
/**//*example1---------*/ 
 
MethodInfo method = type.GetMethod("WriteString");  
 
string test = "test";  
int i = 1;  
 
Object[] parametors = new Object[]{test,i};  
 
//Since the WriteTest Class is not Static you should Create the instance of this class  
obj = ass.CreateInstance("ReflectionTest.WriteTest");  
 
method.Invoke(  
obj,//Instance object of the class need to be reflect  
parametors);//Parametors of indicated method  
 
//method.Invoke(any, parametors);//RuntimeError: class reference is wrong  
 
/**//*example2----------*/ 
   
method = type.GetMethod("StaticWriteString");  
 
//The first parametor will be ignored  
method.Invoke(null, new string[] { "test"});  
method.Invoke(obj, new string[] { "test"});//indicates the instance will equals above line  
method.Invoke(any, new string[] { "test"});//Even the class reference is wrong  
 
/**//*example3-----------*/ 
 
method = type.GetMethod("NoneParaWriteString");  
 
//Sine the method NoneParaWriteString()   
 
has no parametors so do not indicate any parametors  
method.Invoke(null, null);  
 
}  
}  

1 2  下一页

Tags:反射 概念 以及

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接