在開發WCF過程中,我們總是會遇到使用[DataContract]、[ServiceContract]、[OperationContract]來描述或者說是規范類,但是一直不知道這些事干啥用的,怎么獲取這些我們設定的值,也就是如何驗證某一個類的namespace是不是我們規定范圍內的。先看一段代碼:
1 [DataContract(IsReference=true,Name="MyUser",Namespace="http://oec2003.cnblogs.com")] 2 public class User 3 { 4 [DataMember(EmitDefaultValue=true,IsRequired=true, Name="Oec2003_Age",Order=1)] 5 public int Age { get; set; } 6 [DataMember(EmitDefaultValue = true, IsRequired = true, Name = "Oec2003_Name", Order = 2)] 7 public string Name { get; set; } 8 [DataMember(EmitDefaultValue = true, IsRequired = false, Name = "Oec2003_Email", Order = 3)] 9 public string Email { get; set; } 10 }
分別看一下如何獲取屬性值
1.類屬性
上例中類的描述類為:DataContractAttribute,參考MSDN文檔:http://msdn.microsoft.com/zh-cn/library/System.Runtime.Serialization.DataContractAttribute(v=vs.110).aspx
我們可以看出該類未提供任何方法使我們能夠獲取一個已定義類的屬性值,該類集成了System.Attribute,
Attribute類提供了方法Attribute.GetCustomAttribute 方法,先看看MSDN的介紹:檢索應用於程序集、模塊、類型成員或方法參數的指定類型的自定義屬性。
好吧,這個就是我們要找的東西。使用示例:
1 DataContractAttribute dcAttr = (DataContractAttribute)Attribute.GetCustomAttribute(typeof(User), typeof(DataContractAttribute));
2.屬性屬性
讀着有點拗口,前一個屬性是類的成員變量,后一個屬性是描述或者是規范改成員變量的屬性。
MemberInfo.GetCustomAttributes 方法 (Boolean)
PropertyInfo.GetCustomAttributes(false)
1 DataMemberAttribute dmAttr = (DataMemberAttribute)pInfo.GetCustomAttributes(false)[0];
3.方法屬性
如下測試類:
1 public class TestClass 2 { 3 // Assign the Obsolete attribute to a method. 4 [Obsolete("This method is obsolete. Use Method2 instead.")] 5 public void Method1() 6 {} 7 public void Method2() 8 {} 9 }
調用:
1 Type clsType = typeof(TestClass); 2 // Get the MethodInfo object for Method1. 3 MethodInfo mInfo = clsType.GetMethod("Method1"); 4 ObsoleteAttribute obsAttr = (ObsoleteAttribute)Attribute.GetCustomAttribute(mInfo, typeof(ObsoleteAttribute));
4.參數屬性
測試類:
1 public class BaseClass 2 { 3 // Assign an ArgumentUsage attribute to the strArray parameter. 4 // Assign a ParamArray attribute to strList using the params keyword. 5 public virtual void TestMethod( 6 [ArgumentUsage("Must pass an array here.")] 7 String[] strArray, 8 params String[] strList) 9 { } 10 }
調用:
1 Type clsType = typeof( DerivedClass ); 2 MethodInfo mInfo = clsType.GetMethod("TestMethod"); 3 // Iterate through the ParameterInfo array for the method parameters. 4 ParameterInfo[] pInfoArray = mInfo.GetParameters(); 5 foreach( ParameterInfo paramInfo in pInfoArray ) 6 { 7 ArgumentUsageAttribute usageAttr = (ArgumentUsageAttribute)Attribute.GetCustomAttribute(paramInfo, typeof(ArgumentUsageAttribute) ); 8 }
