特性Attributes
using System;
using System.Reflection;
namespace Con_Attribute
{
class Program
{
static void Main(string[] args)
{
//方法一:使用反射来读取 Attribute
// Student student = new Student();
// System.Reflection.MemberInfo info = typeof(Student); //通过反射得到student类的信息
//Hobby hobbyattr = (Hobby)Attribute.GetCustomAttributes(info)[0];
//Hobby hobbyattr = (Hobby)Attribute.[0];
//方法二:使用反射来读取 Attribute
Student instence = new Student();
Type type = instence.GetType();
// PropertyInfo[] vv = type.GetProperties();
// PropertyInfo[] vv = typeof(Student).GetProperties();不需要实例化,可以直接进行寻找
MemberInfo vv = type.GetField("profession");//字段
var gg= vv.GetCustomAttributes(false);
//if (hobbyAttr != null)
//{
// Console.WriteLine("类名:{0}",type.Name);
// //Console.WriteLine("类名:{0}", info.Name);
// Console.WriteLine("兴趣类型:{0}", hobbyAttr.Type);
// Console.WriteLine("兴趣指数:{0}", hobbyAttr.Level);
//}
}
}
//注意:"Sports"是给构造函数的赋值,Level = 5 是给属性的赋值。
//[Hobby("Sports", Level = 5)]
class Student
{
[Hobby("Football", Level = 10)]
public string profession;
public string Profession
{
get { return profession; }
set { profession = value; }
}
}
//建议取名:HobbyAttribute
// [AttributeUsage(AttributeTargets.Field )]
class Hobby : Attribute // 必须以System.Attribute 类为基类
{
// 参数值为null的string是危险的,所以必需在构造函数中赋值
public Hobby(string _type) // 定位参数
{
this.type = _type;
}
//兴趣类型
private string type;
public string Type
{
get { return type; }
set { type = value; }
}
//兴趣指数
private int level;
public int Level
{
get { return level; }
set { level = value; }
}
}
}