????C#?????Attribute???????????л?????????????????????????÷?????л???????????????????
????1??????????????????Attribute
1     [AttributeUsage(AttributeTargets.All)]
2     public sealed class NameAttribute : Attribute
3     {
4         private readonly string _name;
5
6         public string Name
7         {
8             get { return _name; }
9         }
10
11         public NameAttribute(string name)
12         {
13             _name = name;
14         }
15     }
????2????????????NameAttribute????
????1     [Name("dept")]
????2     public class CustomAttributes
????3     {
????4         [Name("Deptment Name")]
????5         public string Name { get; set; }
????6
????7         [Name("Deptment Address")]
????8         public string Address;
????9     }
????3?????CustomAttributes?????"dept"??????
????1         private static string GetName()
????2         {
????3             var type = typeof(CustomAttributes);
????4
????5             var attribute = type.GetCustomAttributes(typeof(NameAttribute)?? false).FirstOrDefault();
????6
????7             if (attribute == null)
????8             {
????9                 return null;
????10             }
????11
????12             return ((NameAttribute)attribute).Name;
????13         }
??????????????????????????Attribute???????????????????????????????????????????Attribute???????????????Address???Attribute???????е???????????????????????????
1         private static string GetAddress()
2         {
3             var type = typeof (CustomAttributes);
4
5             var fieldInfo = type.GetField("Address");
6             if (fieldInfo == null)
7             {
8                 return null;
9             }
10
11             var attribute = fieldInfo.GetCustomAttributes(typeof(NameAttribute)?? false).FirstOrDefault();
12
13             if (attribute == null)
14             {
15                 return null;
16             }
17
18             return ((NameAttribute) attribute).Name;
19         }