• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
AnsonWu的博客
博客园    首页    新随笔    联系   管理    订阅  订阅

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

反射(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!"
;
        }

    }
}
posted @ 2007-04-05 13:53  AnsonWu  阅读(336)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3