WindowsPhone8.1:如何将数据注释添加到枚举值类型以获得适当的字符串

本文关键字:类型 字符串 枚举 添加 注释 数据 WindowsPhone8 | 更新日期: 2023-09-27 18:22:20

我有一个Windows通用应用程序,里面有一个枚举。我在Windows 8.1和Windows Phone 8.1项目中都使用这个枚举。

我已经看过这些链接Windows Phone 8-枚举&数据注释但这似乎适用于Windows Phone 8 Silverlight

这是我的枚举

   enum MyEnum
    {
         [Display(Description="Move forward")]
         Forward,
         [Display(Description="Move Backward")]
         Backward
    }

EnumHelper获取枚举值并返回描述,如下所示

    public static T GetAttribute<T>(this Enum enumValue)
        where T : Attribute
    {
        return enumValue
            .GetType()
            .GetTypeInfo()
            .GetDeclaredField(enumValue.ToString())
            .GetCustomAttribute<T>();
    }

我调用GetAttribute从枚举中获取字符串。我在显示数据时使用此选项,而不是将枚举显示为字符串,而是显示描述注释名称中的字符串。

我能够为Windows 8.1编写一个转换器,它可以采用枚举值并在注释Display中给我描述。然而,我无法在Windows Phone 8.1中实现相同的行为。

在Windows8.1中,以下命名空间将帮助我

using System.ComponentModel.DataAnnotations;

然而,由于它不在Windows Phone 8.1中。我如何实现类似的行为?有变通办法吗?

WindowsPhone8.1:如何将数据注释添加到枚举值类型以获得适当的字符串

如果在使用DisplayAttribute类时不依赖任何特殊行为(由任何其他库引起),则可以创建自己的版本。

using System;
[AttributeUsage(AttributeTargets.All)]
public class DisplayAttribute : System.Attribute 
{
    public string Name { get; private set; }
    public DisplayAttribute(string name)
    {
        this.Name = name;
    }
}

现在您不应该需要System.ComponentModel.DataAnnotations名称空间。