zoukankan      html  css  js  c++  java
  • C#反射方法示例

    假设你的类名是MyClass,方法名是Add

    object obj = Assembly.Load(程序集).CreateInstance("MyNamespace.MyClass", false);

    object obj2 = Type.GetType("MyNamespace.MyClass").GetMethod("Add").Invoke(obj,null);

    obj2 是返回值,

    举例:
    namespace MyNamespace
        public class MyClass
        {
            public int Add(int a, int b)
            {
                return a + b;
            }
        }
    }

    反射:
    object obj = Assembly.GetExecutingAssembly().CreateInstance("MyNamespace.MyClass", false);

    object obj2 = Type.GetType("MyNamespace.MyClass").GetMethod("Add").Invoke(obj, new object[] { 1, 2 });

    int res = (int)obj2;//res =3

    注意:MyClass类名之前要加上类的命名空间,即类的完全限定名。

         Assembly assembly = Assembly.GetExecutingAssembly(); // 获取当前程序集
                object obj = assembly.CreateInstance("反射方法.MyClass", false);
                object obj2 = Type.GetType("反射方法.MyClass").GetMethod("Add").Invoke(obj, new object[] { 1, 2 });

  • 相关阅读:
    NewWords/13001400
    UIWebView加载Js以及Css文件
    驾校错题集合
    NewWords/15001600
    javascript动态添加、修改、删除对象的属性和方法
    NewWords/12001300
    NewWords/11001200
    NewWords/16001700
    NewWords/14001500
    JS与iOS之间的通信
  • 原文地址:https://www.cnblogs.com/hs0811/p/3185102.html
Copyright © 2011-2022 走看看