CustomAttribute.cs
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]
public class CustomAttribute : Attribute
{
public CustomAttribute()
{ }
public CustomAttribute(string remark)
{ }
public string Description;
public int Id { get; set; }
public void ShowRemark()
{ }
}
public class CustomChildAttribute : CustomAttribute
{
}
Student.cs
[Custom("学员父类", Id = 3, Description = "这里是字段")]
public class Student
{
[Custom("学员父类ID", Id = 4, Description = "这里是字段ID")]
public int Id { get; set; }
public string Name { get; set; }
public virtual void Study()
{ }
}
[Custom("vip学员", Id = 3, Description = "这里是付费学员")]
public class StudentVip : Student
{
[Custom("学员父类ID", Id = 4, Description = "这里是字段ID")]
public int LessonId { get; set; }
public int Price { get; set; }
[Custom("学员父类ID", Id = 4, Description = "这里是字段ID")]
public override void Study()
{
Console.WriteLine("学习vip课程");
//CustomAttribute attibute = new CustomAttribute();
//attibute.ShowRemark();
}
//public int Description { get; set; }
}
public class StudentFree : Student
{
public int LessonId { get; set; }
public override void Study()
{
Console.WriteLine("学习公开课");
}
}
public class AttributeShow
{
public static void ShowStudent<T>(T t) where T : Student
{
Type type = t.GetType();
object[] oAttribuyteArray = type.GetCustomAttributes(typeof(CustomAttribute), true);
if (oAttribuyteArray != null && oAttribuyteArray.Length > 0)
{
CustomAttribute attribute = oAttribuyteArray[0] as CustomAttribute;
attribute.ShowRemark();
t.Id = attribute.Id;
}
t.Study();
}
}
Program main
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("欢迎来到.net高级班vip课程,今天的内容是特性和AOP");
People people = new People();
StudentVip vip = new StudentVip()
{
Id = 11,
LessonId = 62618,
Name = "木偶",
Price = 2299
};
AttributeShow.ShowStudent<StudentVip>(vip);
Console.WriteLine(vip.Id);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.Read();
}
}
截图: