gpt4 book ai didi

c# - 如何从枚举类型的值之一获取字符串形式的枚举类型?

转载 作者:行者123 更新时间:2023-12-02 15:02:59 24 4
gpt4 key购买 nike

我确信这很简单,但我就是无法弄清楚。

我想通过传入枚举的成员之一来返回枚举的类型名称。

我的所有搜索都显示了如何从 int 值获取成员名称,或从字符串值显示名称等。但我找不到任何可以显示如何完成此操作的内容。

string name1 = GetEnumName(Colour.Black)
// should be "Colour"


string name2 = GetEnumName(Flower.Daisy)
//should be "Flower"


public static string GetEnumName(Enum myEnum)
{
// ...what goes here...?
}

public enum Colour
{
Black, White, Pink, Blue
}
public enum Flower
{
Pansy, Daffodil, Daisy
}

最佳答案

您可以使用.GetType().Name

GetType()获取当前实例的类型。它具有 Name 属性。请记住,您还可以使用 .GetType().ToString().GetType().FullName 它将返回对象类型的 namespace +名称.

另外不要忘记,您可以使用 is 关键字来确定对象是否为指定类型。 F.e:

if(myEnum is Flower)

关于c# - 如何从枚举类型的值之一获取字符串形式的枚举类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35043249/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com