C# 反射功能

来源:互联网 发布:unity3d怎么播放动画 编辑:程序博客网 时间:2024/06/05 23:01

C#中的反射使用主要集中在System.Reflection命名空间中,通过获取对象的属性和方法并创建对象来调用对应的函数等功能,方法主要集中在如下类:

MethodInfo:获取类的方法

Type:获取类的类型

ConstructInfo:获取该类的构造方法用于创建对象。

完整的示例如下:

class A    {        public void TestMethod1(string msg)        {            Console.WriteLine("class A::TestMethod1:{0}", msg);            //类内方法反射调用类内的方法            Type className = this.GetType();            MethodInfo method = className.GetMethod("TestMethod2", BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);            method.Invoke(this, new object[] {msg});        }        public void TestMethod2(string msg)        {            Console.WriteLine("class A::TestMethod2:{0}",msg);        }    }    class Program    {        static void Main(string[] args)        {            Type className = Type.GetType("ConsoleApplication1.a", false, true);            MethodInfo method = className.GetMethod("TestMethod1", BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);            ConstructorInfo magicConstruct = className.GetConstructor(Type.EmptyTypes);            object classobj = magicConstruct.Invoke(new object[] { });            method.Invoke(classobj, new object[] { "test abc" });            Console.WriteLine("class:{0}", className.GUID.ToString());            Console.ReadLine();        }    }


0 0