通过反射获取到目标类中的字段属性以及方法
一般可用于获取别人提供的dll 查看dll中有哪些字段属性方法
给自己记录一下反射的使用,说不定哪天项目就用上了
namespace MyInfo
{
internal class MyClass
{
public int a { get; set; }
private string b;
public int c;
public void info()
{
}
}
}
using System;
using System.Reflection;
namespace MyInfo
{
internal class Program
{
static void Main(string[] args)
{
//Type
//方法一
//Type t = typeof(MyClass);
//方法二
MyClass myClass = new MyClass();
Type t = myClass.GetType();
Console.WriteLine(t.Name);
Console.WriteLine(t.Assembly);
Console.WriteLine(t.FullName);
//获取到字段
FieldInfo[] fieldInfo = t.GetFields();
foreach (FieldInfo fil in fieldInfo)
{
Console.WriteLine(fil);
}
//获取到属性
PropertyInfo[] propertyInfos= t.GetProperties();
foreach (PropertyInfo item in propertyInfos)
{
Console.WriteLine(item.Name);
}
//获取方法
MethodInfo[] methodInfos = t.GetMethods();
foreach (MethodInfo method in methodInfos)
{
Console.WriteLine(method.Name);
}
Console.WriteLine("Hello World!");
}
}
}