【问题标题】:C# Enum.ToString() with complete name具有完整名称的 C# Enum.ToString()
【发布时间】:2013-09-19 09:18:49
【问题描述】:

我正在寻找一个解决方案来获取枚举的完整字符串。

例子:

Public Enum Color
{
    Red = 1,
    Blue = 2
}
Color color = Color.Red;

// This will always get "Red" but I need "Color.Red"
string colorString = color.ToString();

// I know that this is what I need:
colorString = Color.Red.ToString();

那么有解决办法吗?

【问题讨论】:

  • Color.Red.ToString() 也会返回 Red

标签: c# enums tostring


【解决方案1】:
public static class Extensions
{
    public static string GetFullName(this Enum myEnum)
    {
      return string.Format("{0}.{1}", myEnum.GetType().Name, myEnum.ToString());
    }
}

用法:

Color color = Color.Red;
string fullName = color.GetFullName();

注意:我认为GetType().NameGetType().FullName 更好

【讨论】:

  • 好一个!我用这个!!
  • 语法更新为:return $"{myEnum.GetType().Name}.{myEnum}";
【解决方案2】:

试试这个:

        Color color = Color.Red;

        string colorString = color.GetType().Name + "." + Enum.GetName(typeof(Color), color);

【讨论】:

  • 非常抱歉。 I thought Color is System.Drawing.Color
【解决方案3】:

适用于每个枚举的快速变体

public static class EnumUtil<TEnum> where TEnum : struct
{
    public static readonly Dictionary<TEnum, string> _cache;

    static EnumUtil()
    {
        _cache = Enum
            .GetValues(typeof(TEnum))
            .Cast<TEnum>()
            .ToDictionary(x => x, x => string.Format("{0}.{1}", typeof(TEnum).Name, x));
    }

    public static string AsString(TEnum value)
    {
        return _cache[value];
    }
}

【讨论】:

    【解决方案4】:

    我不知道这是否是最好的方法,但它确实有效:

    string colorString = string.Format("{0}.{1}", color.GetType().FullName, color.ToString())
    

    【讨论】:

      【解决方案5】:
       colorString = color.GetType().Name + "." + color.ToString();
      

      【讨论】:

        【解决方案6】:

        您可以使用扩展方法。

        public static class EnumExtension
        {
            public static string ToCompleteName(this Color c)
            {
                return "Color." + c.ToString();
            }
        }
        

        现在下面的方法将返回“Color.Red”。

        color.ToCompleteName();
        

        http://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-09-26
          • 1970-01-01
          • 1970-01-01
          • 2015-01-25
          • 1970-01-01
          • 2011-03-24
          相关资源
          最近更新 更多