2013-03-01 58 views
0

我有一个扩展方法,允许我为我的枚举添加一个Description属性。有没有办法可以避免在使用枚举时添加System.ComponentModel namspace?

一个典型的枚举看起来是这样的:

public enum Legal 
{ 
    [Description("INVALID!")] 
    None = 0, 
    [Description("general-terms")] 
    General = 1, 
    [Description("competition-terms")] 
    Competition = 2, 
    [Description("privacy-policy")] 
    Privacy = 3, 
    [Description("cookie-policy")] 
    Cookies = 4 
} 

当使用枚举(并已增加其命名空间),我仍然觉得我需要我到处都用它添加System.ComponentModel命名空间。有没有办法解决?

这里的扩展方法:

public static string Description(this Enum @this) 
    { 
     @this.ThrowNull("@this"); 

     var memInfo = @this.GetType().GetMember(@this.ToString()); 

     if (memInfo.IsNotNullOrEmpty()) 
     { 
      var attribute = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false); 

      if (attribute.IsNotNullOrEmpty()) 
       return ((DescriptionAttribute)attribute[0]).Description; 
     } 

     return null; 
    } 

感谢。

回答

0

如果您需要使用description属性,则必须引用它的名称空间。但是,我很少使用该属性。从代码文档的角度来看,简单的智能感知(XML)评论工作得很好,IMO。

[Flags] 
public enum PetTypes 
{ 
    /// <summary>An option for cats!</summary> 
    Cats = 1, 

    /// <summary>An option for dogs!</summary> 
    Dogs = 2 

    /// <summary>Bill Murray style</summary> 
    MassHysteria = 3 
} 
+0

我使用的描述,我需要提高正常的描述。通常我在用第三部分提供的固定列表来开玩笑,但哪一个应该是枚举。 – dotnetnoob 2013-03-01 15:13:02

相关问题