2013-05-30 40 views
2

我有以下的自定義屬性:可以在編譯時評估C#自定義屬性嗎?

[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] 
sealed public class CLSASafeAttribute : Attribute 
{ 
    public Boolean CLSSafe { get; set; } 
    public CLSASafeAttribute(Boolean safe) 
    { 
     CLSSafe = safe; 
    } 
} 

而下面的枚舉部分:

public enum BaseTypes 
{ 
    /// <summary> 
    /// Base class. 
    /// </summary> 
    [CLSASafe(true)] 
    Object = 0, 

    /// <summary> 
    /// True/false. 
    /// </summary> 
    [CLSASafe(true)] 
    Boolean, 

    /// <summary> 
    /// Signed 8 bit integer. 
    /// </summary> 
    [CLSASafe(false)] 
    Int8 
} 

我現在希望能夠創建一個獨特的類每個枚舉,並且能夠標記它通過查看正在實施的類型作爲CLSSafe。我有以下,這顯然是不正確的,但說明了我的本意:

[CLSASafe((Boolean)typeof(BaseTypes.Object).GetCustomAttributes(typeof(BaseTypes.Object), false))] 
sealed public class BaseObject : Field 
{ 
    public Object Value; 
} 

有(從手動標記的簽名分開)這樣做的呢?

回答

1

我建議您定義的屬性如下:

[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] 
sealed public class CLSASafeAttribute : Attribute { 
    public CLSASafeAttribute(Boolean safe) { 
     CLSSafe = safe; 
    } 
    public CLSASafeAttribute(BaseTypes type) { 
     CLSSafe = IsCLSSafe(type); 
    } 
    public Boolean CLSSafe { 
     get; 
     private set; 
    } 
    public static bool IsCLSSafe(BaseTypes type) { 
     var fieldInfo = typeof(BaseTypes).GetField(typeof(BaseTypes).GetEnumName(type)); 
     var attributes = fieldInfo.GetCustomAttributes(typeof(CLSASafeAttribute), false); 
     return (attributes.Length > 0) && ((CLSASafeAttribute)attributes[0]).CLSSafe; 
    } 
} 

然後,將有可能使用以下聲明:

class Foo { 
    [CLSASafe(BaseTypes.Object)] // CLSSafe = true 
    object someField1; 
    [CLSASafe(BaseTypes.Boolean)] // CLSSafe = true 
    bool someField2; 
    [CLSASafe(BaseTypes.Int8)] // CLSSafe = false 
    byte someField3; 
} 

也好,反正確定具體字段是否安全與否:

BaseTypes baseType = GetBaseType(...type of specific field ...); 
bool isCLSSafe = CLSASafeAttribute.IsCLSSafe(baseType); 
+0

哇,非常感謝!你清楚地知道你的屬性! – IamIC

相關問題