Linux 拨号vps windows公众号手机端

C#字符串和枚举类型怎么互转

lewis 6年前 (2019-11-18) 阅读数 9 #程序编程
文章标签 c#

在C#中,可以使用ToString()方法将枚举类型转换为字符串,也可以使用Enum.Parse()方法将字符串转换为枚举类型。

例如,假设有如下枚举类型:

public enum Fruit
{
    Apple,
    Banana,
    Orange
}

将枚举类型转换为字符串:

Fruit fruit = Fruit.Apple;
string fruitString = fruit.ToString();
Console.WriteLine(fruitString); // 输出:Apple

将字符串转换为枚举类型:

string fruitString = "Banana";
Fruit fruit = (Fruit)Enum.Parse(typeof(Fruit), fruitString);
Console.WriteLine(fruit); // 输出:Banana

需要注意的是,在使用Enum.Parse()方法时,需要确保输入的字符串与枚举类型中的值匹配,否则会抛出异常。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门