C# 获取属性Attribute

在开发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 }
原文地址:https://www.cnblogs.com/zhuhc/p/3450465.html