具有完整名称的C#Enum.ToString() [英] C# Enum.ToString() with complete name

查看:132
本文介绍了具有完整名称的C#Enum.ToString()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



示例:

 公开枚举颜色
{
红色= 1,
蓝色= 2
}
颜色color = Color.Red;

//这将永远得到红色,但我需要Color.Red
string colorString = color.ToString();

//我知道这是我需要的:
colorString = Color.Red.ToString();

那么有解决方案吗?

解决方案

  public static class Extensions 
{
public static string GetFullName(this Enum myEnum)
{
返回string.Format({0}。{1},myEnum.GetType()。Name,myEnum.ToString());
}
}

用法:

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

注意:我认为 GetType()。Name 更好的是 GetType()。FullName


I am searching a solution to get the complete String of an enum.

Example:

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();

So is there a solution?

解决方案

public static class Extensions
{
    public static string GetFullName(this Enum myEnum)
    {
      return string.Format("{0}.{1}", myEnum.GetType().Name, myEnum.ToString());
    }
}

usage:

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

Note: I think GetType().Name is better that GetType().FullName

这篇关于具有完整名称的C#Enum.ToString()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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