C#?????Attribute??????????
???????????? ???????[ 2015/11/11 13:15:08 ] ????????.NET ???????????
????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 }
??????
???·???
??????????????????
2023/3/23 14:23:39???д?ò??????????
2023/3/22 16:17:39????????????????????Щ??
2022/6/14 16:14:27??????????????????????????
2021/10/18 15:37:44???????????????
2021/9/17 15:19:29???·???????·
2021/9/14 15:42:25?????????????
2021/5/28 17:25:47??????APP??????????
2021/5/8 17:01:11