C#反射的运用

1:获取相关类的类型
必须是该类的完整路径 参数规则为:命名空间.类+子类
1>非DLL形式的类库,可以看到源代码的 
使用Type.GetType方法  例:Type type = Type.GetType("Test.TestStaticReflection");
2>DLL形式的类库
第一步:使用 Assembly.LoadFile方法加载相关的类库
第二步:使用 Assembly对象的GetType方法获取相关的类
2:获取相关类的属性
使用 Type对象的GetProperty方法
3:设置相关静态属性的值
PropertyInfo.SetValue方法 第一,三个参数为null,第二个参数就是需要给定设置的值
4:获取该类的静态方法
使用 Type对象的GetMethod方法
5:调用该类的静态方法
调用MethodInfo对象的Invoke方法,第一个参数为null,第二个参数为该方法所要传入的参数
例:
namespace Test
{
    public class TestStaticReflection
    {
        public static string Company { get; set; }
        public static void Test()
        {
            Company = "Lazer";
            Console.WriteLine(Company);
            typeof(TestStaticReflection).GetProperty("Company").SetValue(null, "Test", null);
            Type type = Type.GetType("Test.TestStaticReflection");
            type.GetProperty("Company").SetValue(null, "Test", null);
            Console.WriteLine(Company);
            InnerClass.TestString = "LazerInner";
            Console.WriteLine(InnerClass.TestString);
            Console.WriteLine(typeof(TestStaticReflection.InnerClass).FullName);
            Type typeInner = Type.GetType("Test.TestStaticReflection+InnerClass");
            Console.WriteLine(typeInner==null);
            typeInner.GetProperty("TestString").SetValue(null,"LazerInnerSecond",null);
            Console.WriteLine(InnerClass.TestString);
        }
        class InnerClass
        {
            public static string TestString { get; set; }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/liulei199079/article/details/50674249