2009-02-16 38 views
69

我正在使用從屬性類繼承的自定義屬性。我使用它是這樣的:如何創建重複的允許屬性

[MyCustomAttribute("CONTROL")] 
    [MyCustomAttribute("ALT")] 
    [MyCustomAttribute("SHIFT")] 
    [MyCustomAttribute("D")] 
    public void setColor() 
{ 

} 

但顯示「重複'MyCustomAttribute'屬性」錯誤。
如何創建重複允許的屬性?

回答

132

AttributeUsage屬性到您的屬性的類(是的,這是滿口),並設置AllowMultipletrue:但是

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] 
public sealed class MyCustomAttribute: Attribute 
+5

只是好奇 - 爲什麼一個「密封」的課? – 2009-02-16 15:09:12

+15

Microsoft建議儘可能密封屬性類:http://msdn.microsoft.com/en-us/library/2ab31zeh.aspx – 2009-02-16 15:11:02

16

AttributeUsageAttribute ;-p

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] 
public class MyAttribute : Attribute 
{} 

注意的是,如果你是使用ComponentModel(TypeDescriptor),它僅支持每個成員的一個屬性實例(每個屬性類型);原始反射支持任意數量...

3

作爲替代方案,考慮重新設計屬性以允許序列。

[MyCustomAttribute(Sequence="CONTROL,ALT,SHIFT,D")] 

[MyCustomAttribute("CONTROL-ALT-SHIFT-D")] 

然後解析值來配置你的屬性。

有關此示例,請檢查ASP.NET MVC源代碼中的AuthorizeAttribute www.codeplex.com/aspnet

11

Anton's solution是正確的,但有another gotcha

總之,除非您的自定義屬性覆蓋TypeId,否則通過PropertyDescriptor.GetCustomAttributes()訪問它只會返回屬性的單個實例。

1

添加完AttributeUsage,請確保您將此屬性添加到您的屬性類

public override object TypeId 
{ 
    get 
    { 
    return this; 
    } 
} 
2

默認情況下,Attribute s的限制爲僅應用於一次單場/屬性/等。您可以從definition of the Attribute class on MSDN看到這一點:

[AttributeUsageAttribute(..., AllowMultiple = false)] 
public abstract class Attribute : _Attribute 

因此,正如其他人所指出的,所有的子類都以同樣的方式限制,如果您需要在同一個屬性的多個實例,你需要明確設置AllowMultipletrue

[AttributeUsage(..., AllowMultiple = true)] 
public class MyCustomAttribute : Attribute 

在屬性,允許多種用途,you should also override the TypeId property確保性能,如PropertyDescriptor.Attributes按預期方式工作。要做到這一點最簡單的方法是實現屬性返回屬性實例本身:

[AttributeUsage(..., AllowMultiple = true)] 
public class MyCustomAttribute : Attribute 
{ 
    public override object TypeId 
    { 
     get 
     { 
      return this; 
     } 
    } 
} 

(發佈這個答案不是因爲別人是錯的,但因爲這是一個比較全面的/經典的答案。)