示例类
abstract class Base
{
public int Id;
public string Name;
public void SetId(byte b1, byte b2) { Id = b1 * b2; }
public abstract void SetId(int i);
}
class Child : Base
{
public new int Id;
private int hp;
public int Hp
{
get => hp; set
{
if (value > 0)
{ hp += value; }
else if (-value > Def)
{ hp += value - Def; }
}
}
public static int Atk { get; set; }
private static int Def { get; set; }
public override void SetId(int i) { Id = i; }
}
成员的属性
Type t1 = typeof(Child);
MemberInfo m1 = t1.GetMembers()[0];
Console.WriteLine(m1.Name);//获取成员名字
Console.WriteLine(m1.MetadataToken);//获取一个标识符。例如Child类的Id,和Base类的Id是同名同类型的。但他们的标识符不同。
Console.WriteLine(m1.DeclaringType);//获取声明类
Console.WriteLine(m1.ReflectedType);//获取取得这个成员的Type。例如Child从Base继承了Id。
//从Child的Type获取的话就会的到Child。但声明类是Base。
Console.WriteLine(m1.MemberType);//一个枚举,指示这个成员的类型(字段,属性,方法,构造器,事件)
字段和属性的属性
FieldInfo f1 = t1.GetField("Id");
Console.WriteLine(f1.IsPrivate);//访问修饰符是private
Console.WriteLine(f1.IsFamilyAndAssembly);//访问修饰符是protected private
Console.WriteLine(f1.IsFamily);//访问修饰符是protected
Console.WriteLine(f1.IsFamilyOrAssembly);//访问修饰符是protected internal
Console.WriteLine(f1.IsPublic);//访问修饰符是public
Console.WriteLine(f1.IsStatic);//有static修饰
Console.WriteLine(f1.IsInitOnly);//有readonly修饰
PropertyInfo p1 = t1.GetProperty("Hp");
Console.WriteLine(p1.PropertyType);//获取这个属性的Type
Console.WriteLine(p1.CanRead);//这个属性是否有get访问器
Console.WriteLine(p1.CanWrite);//这个属性是否有set访问器
Console.WriteLine(p1.GetGetMethod());//获取这个属性的get访问器,属性是否是静态的,抽象的,都需要从访问器上查看
Console.WriteLine(p1.GetSetMethod());//获取这个属性的set访问器
方法的属性
MethodInfo m = t1.GetMethod("SetId", new Type[] { typeof(int) });
Console.WriteLine(m.IsVirtual);//是否是虚方法
Console.WriteLine(m.IsAbstract);//是否是抽象方法
Console.WriteLine(m.IsStatic);//是否是静态方法
Console.WriteLine(m.IsGenericMethodDefinition);//是否是一个泛型方法
Console.WriteLine(m.ContainsGenericParameters);//是否是还有没填写的泛型参数的泛型方法
ParameterInfo[] para = m.GetParameters();//获取参数列表
Type retype = m.ReturnType;//获取返回类型
ParameterInfo retpar = m.ReturnParameter;//获取详细的返回类型
//公开,私有等同上
检查特性
各成员类的检查特性方法和Type的差不多。
不同的是方法的返回值,参数,和本身三个位置都可以放特性。
参数和返回值需要通过ParameterInfo类获取特性。
m.GetCustomAttribute<Attribute>();//方法的特性
retpar.IsDefined(typeof(Attribute), false);//方法返回值是否具有特性
retpar.GetCustomAttribute(typeof(Attribute));//方法返回值的特性
para[0].IsDefined(typeof(Attribute), false);//方法参数的特性
sealed class MyAttAttribute : Attribute
{
}
abstract class Base
{
public int Id;
public string Name;
public void SetId(byte b1, byte b2) { Id = b1 * b2; }
[return: MyAtt][MyAtt]
public abstract void SetId([MyAtt] int i);
}