使用反射-动态创建对象及调用对象方法

namespace  ConsoleApplication1
ExpandedBlockStart.gifContractedBlock.gif
{
    
public class ReflectionSample
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
private string firstName = string.Empty;
        
private string lastName = string.Empty;

ExpandedSubBlockStart.gifContractedSubBlock.gif        
public ReflectionSample() { }

        
public ReflectionSample(string firstName, string lastName)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
this.firstName = firstName;
            
this.lastName = lastName;
        }


        
public string SayHello()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
return string.Format("Hello {0} {1}"this.firstName, this.lastName);
        }


        
public static string StaticHello()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
return string.Format("Hello, I am a static method");
        }

    }

}


创建对象,方法一:

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gt 1 Assembly asm  =  Assembly.GetExecutingAssembly();
2 Object obj  =  asm.CreateInstance( " ConsoleApplication1.ReflectionSample " true );

 

 

方法二:

 

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gt 1 ObjectHandle handler  =  Activator.CreateInstance( null " ConsoleApplication1.ReflectionSample " ); // 第一个参数表示程序集名称,为null表示当前程序集
2 Object obj  =  handler.Unwrap();

 

带参数构造函数的情况:

创建参数和修改createintance方法:

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gt  1 // 创建参数:
 2 Object[] paras  =   new  Object[ 2 ];
 3 paras[ 0 =   " Jimmy " ;
 4 paras[ 1 =   " Zhang " ;
 5
 6 // 创建对象:
 7 Assembly asm  =  Assembly.GetExecutingAssembly();
 8 Object obj  =  asm.CreateInstance( " ConsoleApplication1.ReflectionSample " true , BindingFlags.Default,  null , paras,  null null );
 9
10 // The second way
11 // ObjectHandle handler = Activator.CreateInstance(null, "ConsoleApplication1.ReflectionSample", true, BindingFlags.Default, null, paras, null, null, null);
12 // Object obj = handler.Unwrap();

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/12639172/viewspace-465894/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/12639172/viewspace-465894/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值