Enum.GetName 方法

定义

重载

GetName(Type, Object)

在指定枚举中检索具有指定值的常数的名称。

GetName<TEnum>(TEnum)

在指定枚举类型中检索具有指定值的常数的名称。

GetName(Type, Object)

Source:
Enum.cs
Source:
Enum.cs
Source:
Enum.cs

在指定枚举中检索具有指定值的常数的名称。

C#
public static string GetName(Type enumType, object value);
C#
public static string? GetName(Type enumType, object value);
C#
[System.Runtime.InteropServices.ComVisible(true)]
public static string GetName(Type enumType, object value);

参数

enumType
Type

枚举类型。

value
Object

特定枚举常量的值(根据其基础类型)。

返回

一个字符串,其中包含 enumType 中值为 value 的枚举常量的名称;或者,如果没有找到这样的常量,则为 null

属性

例外

enumTypevaluenull

enumType 不是 Enum

- 或 -

value 既不属于类型 enumType,也不具有与 enumType 相同的基础类型。

.NET 8 及更高版本: enumType 是一种布尔支持的枚举类型。

示例

以下示例说明了 GetName 的用法。

C#
using System;

public class GetNameTest {
    enum Colors { Red, Green, Blue, Yellow };
    enum Styles { Plaid, Striped, Tartan, Corduroy };

    public static void Main() {

        Console.WriteLine("The 4th value of the Colors Enum is {0}", Enum.GetName(typeof(Colors), 3));
        Console.WriteLine("The 4th value of the Styles Enum is {0}", Enum.GetName(typeof(Styles), 3));
    }
}
// The example displays the following output:
//       The 4th value of the Colors Enum is Yellow
//       The 4th value of the Styles Enum is Corduroy

注解

如果多个枚举成员具有相同的基础值,该方法 GetName 保证将返回其中一个枚举成员的名称。 但是,它不保证始终返回同一枚举成员的名称。 因此,当多个枚举成员具有相同的值时,应用程序代码绝不应依赖于返回特定成员名称的方法。

适用于

.NET 10 和其他版本
产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

GetName<TEnum>(TEnum)

Source:
Enum.cs
Source:
Enum.cs
Source:
Enum.cs

在指定枚举类型中检索具有指定值的常数的名称。

C#
public static string? GetName<TEnum>(TEnum value) where TEnum : struct;

类型参数

TEnum

枚举的类型。

参数

value
TEnum

特定枚举常量的值(根据其基础类型)。

返回

一个字符串,其中包含 TEnum 中值为 value 的枚举常量的名称;或者,如果没有找到这样的常量,则为 null

例外

.NET 8 及更高版本: TEnum 是一种布尔支持的枚举类型。

适用于

.NET 10 和其他版本
产品 版本
.NET 5, 6, 7, 8, 9, 10