现在的位置: 首页 > 综合 > 正文

关于反射的一点理解(一)

2011年12月05日 ⁄ 综合 ⁄ 共 2243字 ⁄ 字号 评论关闭

反射(Reflection)是.NET中的重要机制,通过放射,可以在运行时获得.NET中每一个类型(包括类、结构、委托、接口和枚举等)的成员,包括方法、属性、事件,以及构造函数等。还可以获得每个成员的名称、限定符和参数等。有了反射,即可对每一个类型了如指掌。如果获得了构造函数的信息,即可直接创建对象,即使这个对象的类型在编译时还不知道。

/*
 * Created by SharpDevelop.
 * User: anson.wu
 * Date: 2007-4-5
 * Time: 11:39
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 
*/
using System;
using
 System.Reflection;
using
 System.Data;

namespace ReflectionTest
{
    
class
 MainClass
    {
        
public static void Main(string
[] args)
        {
            Assembly ass;
            Type type;
            
object
 obj;
            
string libPath=@"E:\C#\ReflectLib\bin\Debug\ReflectLib.dll"
;
            
if(!
System.IO.File.Exists(libPath))            
            {
                Console.Write(
"The DLL Is Not Exist!"
);
                Console.Read();
                
return
;
            }
            
try

            {
                ass
=Assembly.LoadFrom(libPath);
                type
=ass.GetType("ReflectLib.TestMethod"
);
                System.Reflection.MethodInfo method
=type.GetMethod("GetLibVersion"
);
                obj
=ass.CreateInstance("ReflectLib.TestMethod"
);
                
//调用GetLibVersion方法

                Console.WriteLine(method.Invoke(obj,null));
                
//调用Add方法

                method=type.GetMethod("Add");
                
object[] par = new object[] {4,5
};
                Console.WriteLine(method.Invoke(obj,par));
                
//调用静态方法

                method=type.GetMethod("GetWelcome");
                Console.WriteLine(method.Invoke(
null,null
));        

            }
            catch
(Exception e)
            {
                Console.Write(e.Message);
            }
            
        }
    }
}

外部程序集代码

/*
 * Created by SharpDevelop.
 * User: anson.wu
 * Date: 2007-4-5
 * Time: 11:36
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 
*/
using System;
namespace
 ReflectLib
{
    
/// <summary>

    
/// Description of MyClass.
    
/// </summary>

    public class TestMethod
    {
        
public string
 GetLibVersion()
        {
            
return "Current Version 1.0.2"
;
        }
        
public int Add(int x,int
 y)
        {
            
return x+
y;
        }
        
public static string
 GetWelcome()
        {
            
return "Hello , C# Reflect!"
;
        }

    }
}

抱歉!评论已关闭.