可移植类库中的System.ComponentModel.DescriptionAttribute

Cru*_*ler 23 c# dll portable-class-library

我在枚举中使用Description属性为枚举字段提供用户友好名称.例如

public enum InstallationType
{
    [Description("Forward of Bulk Head")]
    FORWARD = 0,

    [Description("Rear of Bulk Head")]
    REAR = 1,

    [Description("Roof Mounted")]
    ROOF = 2,
}
Run Code Online (Sandbox Code Playgroud)

使用一个很好的帮助方法很容易访问它:

public static string GetDescriptionFromEnumValue(Enum value)
    {
        DescriptionAttribute attribute = value.GetType()
            .GetField(value.ToString())
            .GetCustomAttributes(typeof(DescriptionAttribute), false)
            .SingleOrDefault() as DescriptionAttribute;
        return attribute == null ? value.ToString() : attribute.Description;
    }
Run Code Online (Sandbox Code Playgroud)

我需要将其转换为可移植的类库,但它似乎无法访问System.ComponentModel库.当我尝试添加一个崇敬的VS时告诉我,我已经引用了所有内容.

谢谢

Jeh*_*hof 27

由于DescriptionAttribute不适用于可移植类库,因此您需要使用其他属性.System.ComponentModel.DataAnnotations可用于可移植类库的命名空间提供了可以使用的属性DisplayAttribute.

public enum InstallationType
{
    [Display(Description="Forward of Bulk Head")]
    FORWARD = 0,

    [Display(Description="Rear of Bulk Head")]
    REAR = 1,

    [Display(Description="Roof Mounted")]
    ROOF = 2,
}
Run Code Online (Sandbox Code Playgroud)

您的方法需要更改为

public static string GetDescriptionFromEnumValue(Enum value)
    {
        DisplayAttribute attribute = value.GetType()
            .GetField(value.ToString())
            .GetCustomAttributes(typeof(DisplayAttribute ), false)
            .SingleOrDefault() as DisplayAttribute ;
        return attribute == null ? value.ToString() : attribute.Description;
    }
Run Code Online (Sandbox Code Playgroud)


Mar*_*ell 16

可移植类库是否可用某些内容取决于您为库选择的框架 - 您只能获得严格的交集.但是,很可能这个属性在您的某个目标框架中根本不存在.在这种情况下,一个选项是添加自己的 - 然后你知道它是可用的.例如:

[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class EnumDescriptionAttribute :Attribute
{
    private readonly string description;
    public string Description { get { return description; } }
    public EnumDescriptionAttribute(string description)
    {
        this.description = description;
    }
}

enum Foo
{
    [EnumDescription("abc")]
    A,
    [EnumDescription("def")]
    B
}
Run Code Online (Sandbox Code Playgroud)

请注意,我故意没有在此处包含其他序列化构造函数,因为它们也依赖于所有框架上都不可用的功能.将代码从使用[Description]/ 更改DescriptionAttribute为[EnumDescription]/ EnumDescriptionAttribute应该是相当简单的.