System.ComponentModel.DescriptionAttribute在便携式类库中 [英] System.ComponentModel.DescriptionAttribute in portable class library

查看:542
本文介绍了System.ComponentModel.DescriptionAttribute在便携式类库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用枚举中的描述属性为枚举域提供了一个用户友好的名称。例如

I am using the Description attribute in my enums to provide a user friendly name to an enum field. e.g.

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

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

    [Description("Roof Mounted")]
    ROOF = 2,
}

帮助方法:

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;
    }

我需要将其转换为便携式类库,但似乎不以访问System.ComponentModel库。当我尝试添加尊敬VS告诉我已经引用了一切。

I need to convert this into a portable class library but it doesn't seem to have access to the System.ComponentModel library. when I try add a reverence VS tells me that I have referenced everything already.

谢谢

推荐答案

由于 DescriptionAttribute 不适用于便携式类库,您需要使用另一个属性。可用于便携式类库的命名空间 System.ComponentModel.DataAnnotations 提供了属性 DisplayAttribute ,您可以使用。

Since DescriptionAttribute is not available for portable class libraries you need to use another attribute. The namespace System.ComponentModel.DataAnnotations which is available for portable class libraries provides the attribute DisplayAttribute that you can use instead.

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,
}

您的方法需要更改为

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;
    }

这篇关于System.ComponentModel.DescriptionAttribute在便携式类库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆