C#枚举的替代名称 [英] Alternative Names for C# enum

查看:142
本文介绍了C#枚举的替代名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我们可以这样声明枚举

  public enum ChangeFlag 
{
NEW(New),
DELETED(Deleted),
REVISED(Revised);

private final String text;

ChangeFlag(String text)
{
this.text = text;
}

public String toString()
{
return text;
}
}

C#有什么优雅的等价物? / p>

编辑:

  public static class FooExtensions 
{
public static string GetDescription(this Foo @this)
{
switch(@this)
{
case Foo.Bar:
returnA bar ;
}
}

}



你能解释GetDescription(这个Foo @this)中的参数是什么意思?
我不习惯看到什么这个Foo @this 指的是

解决方案

您可以使用 DescriptionAttribute

  public enum Foo 
{
[描述(A酒吧)]
酒吧
}

然后您将通过 TypeDescriptor.GetAttributes Type.GetCustomAttributes



或者您可以使用扩展方法:

  public enum Foo 
{
Bar
}

public static class FooExtensions
{
public static string GetDescription(this Foo @this)
{
switch(@this)
{
case Foo.Bar:
returnA bar ;
}
}
}

//消费代码
var foo = Foo.Bar;
var description = foo.GetDescription();

后一种方法还为您提供了对本地化的更多控制,因为您可以随时查看例如资源文件中的描述。


In Java, we can declare enums like so

public enum ChangeFlag
{
    NEW("New"),
    DELETED("Deleted"),
    REVISED("Revised");

    private final String    text;

    ChangeFlag(String text)
    {
        this.text = text;
    }

    public String toString()
    {
        return text;
    }
}

Is there any elegant equivalent to this for C#?

Edit:

public static class FooExtensions
{
public static string GetDescription(this Foo @this)
{
    switch (@this)
    {
        case Foo.Bar:
            return "A bar";
    }
}

}

Could you explain what the parameters in GetDescription(this Foo @this) mean? I'm not used to seeing what this Foo @this refers to

解决方案

You can use DescriptionAttribute:

public enum Foo
{
    [Description("A bar")]
    Bar
}

Which you would then extract via TypeDescriptor.GetAttributes or Type.GetCustomAttributes.

Or you could use extension methods:

public enum Foo
{
    Bar
}

public static class FooExtensions
{
    public static string GetDescription(this Foo @this)
    {
        switch (@this)
        {
            case Foo.Bar:
                return "A bar";
        }
    }
}

// consuming code
var foo = Foo.Bar;
var description = foo.GetDescription();

The latter approach also gives you more control when it comes to localization, since you could always look up the description in a resource file, for example.

这篇关于C#枚举的替代名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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