阅读目录 
   一:C#自定义Attribute

   二:AttributeUsageAttribute中的3个属性(Property)中的AttributeTargets
   三:AttributeUsageAttribute中的3个属性(Property)中的,AllowMultiple
   四:AttributeUsageAttribute中的3个属性(Property)中的Inherited

 一:C#自定义Attribute
  
写一个类继承自System.Attribute就可以了
  二:AttributeUsageAttribute中的3个属性(Property)中的AttributeTargets
     
这个属性类能应用于哪种类型上面,如下图,我的例子中声明属性类HelperAttribute只能用于interface接口上面,而我实际应用于class上面编译就报错了说声明类型不对
  2.C#自定义Attribute-LMLPHP
  2.C#自定义Attribute-LMLPHP
  2.C#自定义Attribute-LMLPHP

 三:AttributeUsageAttribute中的3个属性(Property)中的,AllowMultiple
   能否多次声明指定的属性,如下图AllowMultiple=false的话,我在一个类上声明2次,编辑就报错了
2.C#自定义Attribute-LMLPHP

2.C#自定义Attribute-LMLPHP

四:AttributeUsageAttribute中的3个属性(Property)中的Inherited
我们在父类上声明属性类,而在子类上不声明属性类,把属性类设置为Inherited = false,我们看到查找SubMyClass1类型没有找到它的父类MyClass1的HelperAttribute属性类,所以没有任何输出
2.C#自定义Attribute-LMLPHP

2.C#自定义Attribute-LMLPHP我们改为Inherited = true后,再调试看到查找SubMyClass1类型找到了它父类的HelperAttribute属性类,然后输出描述

2.C#自定义Attribute-LMLPHP

我们在父类上声明属性类,也在子类上声明属性类,把属性类设置为 AllowMultiple = false, Inherited = true,我们看到查找SubMyClass1类型找到了它自己的HelperAttribute属性类,然后输出描述,没有找到父类MyClass1的HelperAttribute属性类,是因为 AllowMultiple = false不允许多重属性,所以父类的HelperAttribute属性类被子类SubMyClass1的HelperAttribute属性类覆盖了,所以最终只能找到子类的属性类

2.C#自定义Attribute-LMLPHP

2.C#自定义Attribute-LMLPHP

我们再改为AllowMultiple = true, Inherited = true,我们看到查找SubMyClass1类型不但是找到了它自己的HelperAttribute属性类而且找到了父类MyClass1的HelperAttribute属性类,所以最终会输出两条信息
2.C#自定义Attribute-LMLPHP

实例代码

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace CustomizeAttribute
{
class Program
{
static void Main(string[] args)
{
foreach (Attribute attr in typeof(SubMyClass1).GetCustomAttributes(true))
{
HelperAttribute helperAtt = attr as HelperAttribute;
if (helperAtt != null)
{
Console.WriteLine("Name:{0} Description:{1}",helperAtt.Name, helperAtt.Description);
}
} Console.ReadLine();
}
} [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public class HelperAttribute : System.Attribute
{
private string _name;
private string _description; public HelperAttribute(string des)
{
this._name = "Default name";
this._description = des;
} public HelperAttribute(string des1,string des2)
{
this._description = des1;
this._description = des2;
} public string Description
{
get
{
return this._description;
}
set
{
this._description = value;
}
} public string Name
{
get
{
return this._name;
}
set
{
this._name = value;
}
} public string PrintMessage()
{
return "PrintMessage";
}
} [HelperAttribute("this is my class1")]
public class MyClass1
{ } public class SubMyClass1 : MyClass1
{ } [HelperAttribute("this is my class2", Name = "myclass2")]
public class MyClass2
{ } [HelperAttribute("this is my class3", Name = "myclass3", Description = "New Description")]
public class MyClass3
{ } [HelperAttribute("this is my class4", "this is my class4")]
public class MyClass4
{ }
}
05-11 10:48