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

 

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

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

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

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Assembly ass;  
Type type;  
Object obj;  
 

Object any 
= new Object();
string test = "test";
int i = 1;
Object[] parametors
= new Object[] { test, i };


ass
= Assembly.LoadFile(@"C:\ReflectTest.dll"); //必须指出的DLL整个路径 
type = ass.GetType("ReflectionTest.WriteTest"); //必须命名空间的类的名称  type用于取得对象的方法
obj = ass.CreateInstance("ReflectionTest.WriteTest");//创建 WriteTest 的实例



//--------------------------------------------------------
MethodInfo method = type.GetMethod("WriteString");

method.Invoke(obj, parametors);
// 实例类需要对象反映 及方法的参数


method.Invoke(any,
new string[] { "test" });//即使类的引用是错误的  
//因为any对象没有这个method
//更简单的理解就是从WriteTest类型中得到的method怎么可以随便绑定到一个对象上呢
 

//------------------------------------------------    
method = type.GetMethod("StaticWriteString");

method.Invoke(
null, new string[] { "test" }); //第一个参数将被忽略  
method.Invoke(obj, new string[] { "test" });//看上去好像和上面一行是一样的  
method.Invoke(any, new string[] { "test" });//即使类的引用是错误的  
// Static方法可以绑定到错误的类型上


//-------------------------------------------------------
method = type.GetMethod("NoneParaWriteString");  

method.Invoke(
null, null);  

Console.ReadLine();
}
}



}

 

posted on 2010-05-11 17:23  Master zhu  阅读(257)  评论(0编辑  收藏  举报

导航