带属性的枚举 vs 带属性的类

Kro*_*owi 1 c# enums

我正在开发一个应用程序,我想知道我是否应该使用Enumwith a StringValueAttributevs a classwith properties。

我的第一种方法是Enum使用StringValueAttribute. 这是我现在使用的方法。通过一种叫做GetStringValue()我能够获得资源价值的方法。

public enum Icon
{
    /// <summary>
    /// The NoruBox contains a symbol consisting of a cardboard box.
    /// </summary>
    [StringValue("/Noru;Component/NoruBox/Media/Box_512.png")]
    Box = 0,

    /// <summary>
    /// The NoruBox contains a symbol consisting of a bust.
    /// </summary>
    [StringValue("/Noru;Component/NoruBox/Media/Person_512.png")]
    Person = 1,

    // More values (total of 5).
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是classwith 类型的属性Icon(它将具有NameResource属性。这也让我可以选择添加一个GetAll()方法,该方法返回一个包含所有可用图标的列表。

public static class Icons
{
    public static List<Icon> GetAll()
    {
        return new List<Icon> { Box, Person, ... };
    }

    public static Icon Box = new Continent("Box", Localizer.GetString("/Noru;Component/NoruBox/Media/Box_512.png"));
    public static Icon Person = new Continent("Person", Localizer.GetString("/Noru;Component/NoruBox/Media/Person_512.png"));
    // More Icons (total of 5).
}
Run Code Online (Sandbox Code Playgroud)

两者中的哪一个是最好的方法,为什么?现在,(尽管我使用的是枚举)类方法在代码中看起来比使用枚举要简洁得多。使用 Enum 我必须输入例如_icon.GetStringValue()_icon.Resource类。

EDIT1:多一点澄清:除了在我的项目中有一个额外的资源参考外,Icon可以与其中一个进行比较MessageBox

Lor*_*rek 5

另一种方法是使用带有扩展方法的枚举,用于您想要与枚举中的项目关联的每个附加属性。考虑以下:

public static class IconInfo
{
    public static string FileName(this Icon icon)
    {
        switch (icon)
        {
            case Icon.Box: return "/Noru;Component/NoruBox/Media/Box_512.png";
            case Icon.Person: return "/Noru;Component/NoruBox/Media/Person_512.png";
            default: return "";
        }
    }
}

public enum Icon
{
    Box = 0,
    Person = 1,
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以迭代类似于以下内容的“所有”值:

        foreach (Icon icon in Enum.GetValues(typeof(Icon)))
        {
            Console.WriteLine(string.Format("{0}:{1}", icon, icon.FileName()));
        }
Run Code Online (Sandbox Code Playgroud)

如果将无效值传递给您的扩展方法之一,您将需要决定是返回默认值还是抛出异常。