using System; using System.Reflection; using System.Collections.Generic; using System.Text; namespace TestSpace { //1)制作标签 public class FriutTypeAttribute : Attribute { public string Note { get { return "所有有苹果都我家种的!"; } } } [FriutType] //2)贴标签 public class Apple { private string _color; public Apple(string color) { _color = color; } public string Color { get { return _color; } } } class DemoClass { static void Main(string[] args) { Apple a = new Apple("红色"); Console.WriteLine("苹果的颜色是:{0} ", a.Color); //3)查看标签上的信息 Type type = a.GetType(); foreach (Attribute attr in Attribute.GetCustomAttributes(type)) { if (attr.GetType() == typeof(FriutTypeAttribute)) Console.WriteLine("显示Apple的相关信息: {0}", ((FriutTypeAttribute)attr).Note); } } } }