c# 反射之 通过反射获取类的属性方法和程序集
1、打开VS,新建一个控制台应用,然后右键添加一个新建项测试类作为反射获取的类对象,具体如下图
2、测试类的包括含公有私有保护类型的字段属性以及方法,以便总结反射获取的一些属性信息的特性,具体如下图
3、通过反射获取测试类的Type,然后获取Type的名称以及命名空间,运行结果如下图
4、获取测试类Type的字段,并运行,从运行结果来看反射只能获取该类Type的公有字段,具体如下图
5、获取测试类Type的属性,并运行,从运行结果来看反射只能获取该类Type的公有属性,具体如下图
6、获取测试类Type的方法函数,并运行,从运行结果来看反射只能获取该类Type的公有方法函数,具体如下图
7、获取测试类Type的程序集并打印程序集全名和类,运行结果如下图
8、TestClass 脚本内容如下:
namespace TestReflection
{
class TestClass
{
public int Age;
protected string name;
private string Address;
public string NameProperty { get; set; }
public string AddressProperty { get; private set; }
public void Func1() { }
protected void Func2() { }
private void Func3() { }
}
}
9、Program 脚本具体内容如下:
using System;
using System.Reflection;
namespace TestReflection
{
class Program
{
static void Main(string[] args)
{
//每一个类对应一个Type,Type中存储了该类的相关信息
TestClass testClass = new TestClass();
Type testClassType = testClass.GetType();
//获取该类Type的名称和命名空间并打印
Console.WriteLine(testClassType.Name);
Console.WriteLine(testClassType.Namespace);
//获取Type公有字段并打印
FieldInfo[] arrayFieldInfo = testClassType.GetFields();
foreach (FieldInfo field in arrayFieldInfo) {
Console.WriteLine(field.Name + " ");
}
//获取Type公有属性并打印
PropertyInfo[] arrayPropertyInfo = testClassType.GetProperties();
foreach (PropertyInfo info in arrayPropertyInfo)
{
Console.WriteLine(info.Name + " ");
}
//获取Type公有方法函数并打印
MethodInfo[] arrayMethodInfo = testClassType.GetMethods();
foreach (MethodInfo info in arrayMethodInfo)
{
Console.WriteLine(info.Name + " ");
}
//获取Type的程序集并打印全名和程序集里面的类型
Assembly assembly = testClass.GetType().Assembly;
Console.WriteLine(assembly.FullName+" ");
Type[] arrayType = assembly.GetTypes();
foreach (Type type in arrayType)
{
Console.WriteLine(type + " ");
}
//避免控制台运行立马结束
Console.ReadKey();
}
}
}