zoukankan      html  css  js  c++  java
  • 使用反射动态创建对象及调用对象方法

    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");
            }

        }

    }


    创建对象,方法一:

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

    方法二:

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

    带参数构造函数的情况:

    创建参数和修改createintance方法:

     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, nullnull);
     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();

    ss

  • 相关阅读:
    dos
    jsf session的获取和添加
    tomcat多开造成的端口占用
    myeclipse中tomcat7内存大小的设置
    中文传值乱码过滤
    java定时器
    jsf中jstl标签<c:forEach/>打印信息
    python基础python函数any()与all()的区别
    C# GetManifestResourceStream获取资源为null
    Linux kill 9 和 kill 15 的区别
  • 原文地址:https://www.cnblogs.com/goody9807/p/1299736.html
Copyright © 2011-2022 走看看