枚举可以返回字符串而不是整数吗? [英] Can enums return string instead of an integer?

查看:204
本文介绍了枚举可以返回字符串而不是整数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的枚举返回字符串值。不是Enum Description,它们必须返回字符串值,而不是int。以下代码示例完全是我的想法,但显然不会编译。

I want my enums to return string values. Not the Enum Description, they must be returning a string value, instead of an int. The code sample below is exactly what in my mind, but obviously doesn't compile.

public enum TransactionType
{
    CreditCard = "C",
    DebitCard = "D",
    CreditCardAuthenticationWithAuthorization = "CA",
    DebitCardAuthenticationWithAuthorization = "DA"
}

有什么想法吗?

推荐答案

您不能,您可以做的是创建一个静态类,使其像字符串枚举的枚举一样起作用:

You can't, what you can do is create a static class that "acts" a bit like an enum with string values:

public static class TransactionType
{
   public const string CreditCard = "C";
   ...
}

您可以按以下方式访问它们:

You can access them the same way then:

string creditCardValue = TransactionType.CreditCard;

另一种选择是使用 System.ComponentModel >名称空间,但是您的枚举仍将具有基础数字值,因此也许这并不是您所需要的全部。

Another option would be to work with the DescriptionAttribute in System.ComponentModel namespace, but then your enums still will have underlying numeric values, so maybe that's not entirely what you need.

示例:

public enum TransactionType
{
   [Description("C")]
   CreditCard,
   ...
}

这篇关于枚举可以返回字符串而不是整数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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