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

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

问题描述

我用我的枚举Description属性提供一个用户友好的名称,一个枚举领域。例如:

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

和访问,这是很容易用一个漂亮的helper方法:

And accessing this is easy with a nice helper method:

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天全站免登陆