反射 学习用例

第一步:新建一个类库项目,命名“ReflectionExample” ,代码:

using  System;
namespace  ReflectionExample
{
    
public   class  HelloWorld
    {
        
string  myName  =   null ;
        
public  HelloWorld( string  name)
        {
            myName 
=  name;
        }
        
public  HelloWorld()
            : 
this ( null )
        { }
        
public   string  Name
        {
            
get
            {
                
return  myName;
            }
        }
        
public   void  SayHello()
        {
            
if  (myName  ==   null )
            {
                System.Console.WriteLine(
" Hello World " );
            }
            
else
            {
                System.Console.WriteLine(
" Hello, "   +  myName);
            }
        }
    }
}

编译,生成一个ReflectionExample.dll文件.

第二步:新建一个项目,命名“Reflection”,添加引用“ReflectionExample.dll”

 

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

namespace  ReflectionExample
{
    
class  Class1
    {
        
// [STAThread]
         static   void  Main( string [] args)
        {
            System.Console.WriteLine(
" 列出程序集中的所有类型 " );
            Assembly a 
=  Assembly.LoadFrom( " ReflectionExample.dll " );
            Type[] mytypes 
=  a.GetTypes();

            
foreach  (Type t  in  mytypes)
            {
                System.Console.WriteLine(t.Name);
            }
            System.Console.ReadLine();
            Console.WriteLine(
" ManifestModule,获取该程序清单的模块:{0} " , a.ManifestModule);
            Console.ReadLine();
            Console.WriteLine(
" CodeBase,获取最初指定程序集的位置:{0} " , a.CodeBase);
            Console.ReadLine();
            Console.WriteLine(
" Entry point,获取此程序集的入口点:{0} " , a.EntryPoint);
            Console.ReadLine();
            System.Console.WriteLine(
" 列出HellWord中的所有方法 " );
            Type ht 
=   typeof (HelloWorld);
            MethodInfo[] mif 
=  ht.GetMethods();
            
foreach  (MethodInfo mf  in  mif)
            {
                System.Console.WriteLine(mf.Name);
            }
            System.Console.ReadLine();
            System.Console.WriteLine(
" 实例化HelloWorld,并调用SayHello方法 " );
            Object obj 
=  Activator.CreateInstance(ht);
            
string [] s  =  {  " zhenlei "  };
            Object bojName 
=  Activator.CreateInstance(ht, s);
            BindingFlags flags 
=  (BindingFlags.NonPublic  |  BindingFlags.Public  |  BindingFlags.Static  |  BindingFlags.Instance  |  BindingFlags.DeclaredOnly);
            MethodInfo msayhello 
=  ht.GetMethod( " SayHello " );
            msayhello.Invoke(obj, 
null );
            msayhello.Invoke(bojName, 
null );
            System.Console.ReadLine();
        }
    }
}

运行结果是:

结果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值