ITPub博客

首页 > Linux操作系统 > Linux操作系统 > 使用反射-动态创建对象及调用对象方法

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

原创 Linux操作系统 作者:iDotNetSpace 时间:2008-09-27 13:33:27 0 删除 编辑
namespace ConsoleApplication1
{
    
public class ReflectionSample
    
{
        
private string firstName = string.Empty;
        
private string lastName = string.Empty;

        
public ReflectionSample() { }

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


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


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

    }

}


创建对象,方法一:

<!--

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

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

 

 

方法二:

 

<!--

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

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

 

带参数构造函数的情况:

创建参数和修改createintance方法:

<!--

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

--> 1//创建参数:
 2Object[] paras = new Object[2];
 3paras[0] = "Jimmy";
 4paras[1] = "Zhang";
 5
 6//创建对象:
 7Assembly asm = Assembly.GetExecutingAssembly();
 8Object 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博客 ” ,链接:https://blog.itpub.net/12639172/viewspace-465894/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2008-01-04

  • 博文量
    2376
  • 访问量
    5765917