gpt4 book ai didi

c# - 如何在(字符串、标志列表、带标志的枚举)之间转换枚举?

转载 作者:太空狗 更新时间:2023-10-29 22:15:43 25 4
gpt4 key购买 nike

如何从枚举转换为字符串,反之亦然?

假设枚举可以包含多个标志,我如何才能获得一个枚举包含的所有标志的列表?

最佳答案

更新2

有一个库可以实现枚举所需的大部分功能,而且性能更好 https://github.com/TylerBrinkley/Enums.NET


从枚举到字符串: [Enum Instance].ToString();

示例:使用 System.Windows.Input;

ModifierKeys mk = ModifierKeys.None | ModifierKeys.Alt | ModifierKeys.Shift | ModifierKeys.Control;
mk.Tostring();

返回:

Alt、Control、Shift注意:“无”标志已删除


从字符串到枚举:

Enum.TryParse([(string) value],out [store variable]);
或者
Enum.Parse(typeof([Enum Type]), [(string) value], [(bool) 应该忽略字符大小写?]);

示例:使用 System.Windows.Input;

// Way 1:
ModifierKeys outenum;
bool successful = Enum.TryParse("None,Alt,Control,Shift", out outenum);

Console.WriteLine($"Is Successful ? : {successful}, result : {outenum.ToString()}");

结果:是否成功? : True, 结果 : Alt, Control, Shift

// Way 2:
ModifierKeys outenum = (ModifierKeys)Enum.Parse(typeof(ModifierKeys), "None,Alt,Control,Shift", true);
Console.WriteLine(outenum.ToString());

结果:Alt、Control、Shift


从枚举标志到列表

例子:

        ModifierKeys mk = ModifierKeys.None | ModifierKeys.Alt | ModifierKeys.Shift | ModifierKeys.Control;
List<ModifierKeys> mklist =
mk
.ToString() // Convert the enum to string
.Split(new[] { "," } , StringSplitOptions.RemoveEmptyEntries) // Converts the string to Enumerable of string
.Select(//converts each element of the list to an enum, and makes an Enumerable out of the newly-converted items
strenum =>
{
ModifierKeys outenum;
Enum.TryParse(strenum , out outenum);
return outenum;
})
.ToList(); // Creates a List from the Enumerable

结果:{ModifierKeys.Alt,ModifierKeys.Shift,ModifierKeys.Control}


从枚举标志列表到枚举

例子:

 ModifierKeys[] mk = {ModifierKeys.None, ModifierKeys.Alt, ModifierKeys.Control, ModifierKeys.Shift};
ModifierKeys mkc = mk.Aggregate((prev, next) => prev | next);
Console.WriteLine(mkc.ToString());

结果:Alt、Control、Shift


从字符串列表到枚举

例子:

    string[] mk = {"None", "Alt", "Control", "Shift"};
ModifierKeys mkc = mk.Select(x => {ModifierKeys outenum; Enum.TryParse(x, out outenum); return outenum;}).Aggregate((prev , next) => prev | next);
Console.WriteLine(mkc.ToString());

结果:Alt、Control、Shift


一般注意事项:

  • 字符串转枚举优先使用方式一,因为方式二失败会抛出异常,方式一失败则返回false
  • 在解析枚举字符串时分隔枚举标志时,仅使用, 分隔符
  • 枚举字符串中的标志之间有空格无关紧要,所以“无,Alt,Control,Shift” = “无,Alt,Control,Shift”

更新 1:

我写了一个简单的 Generic EnumConverter 类,可以节省您的时间

public class EnumConverter<T> where T : struct, IConvertible, IFormattable
{
private Type EnumType { get; set; }

public Type UnderlyingType
{
get
{
return Enum.GetUnderlyingType(EnumType);
}
}
public EnumConverter()
{
if (typeof(T).IsEnum)
EnumType = typeof(T);
else
throw new ArgumentException("Provided type must be an enum");
}
public IEnumerable<T> ToFlagsList(T FromSingleEnum)
{
return FromSingleEnum.ToString()
.Split(new[] { "," } , StringSplitOptions.RemoveEmptyEntries)
.Select(
strenum =>
{
T outenum = default(T);
Enum.TryParse(strenum , true , out outenum);
return outenum;
});
}
public IEnumerable<T> ToFlagsList(IEnumerable<string> FromStringEnumList)
{
return FromStringEnumList
.Select(
strenum =>
{
T outenum = default(T);
Enum.TryParse(strenum , true , out outenum);
return outenum;
});
}

public T ToEnum(string FromString)
{
T outenum = default(T);
Enum.TryParse(FromString , true , out outenum);
return outenum;
}
public T ToEnum(IEnumerable<T> FromListOfEnums)
{
var provider = new NumberFormatInfo();
var intlist = FromListOfEnums.Select(x => x.ToInt32(provider));
var aggregatedint = intlist.Aggregate((prev , next) => prev | next);
return (T)Enum.ToObject(EnumType , aggregatedint);
}
public T ToEnum(IEnumerable<string> FromListOfString)
{
var enumlist = FromListOfString.Select(x =>
{
T outenum = default(T);
Enum.TryParse(x , true , out outenum);
return outenum;
});
return ToEnum(enumlist);
}

public string ToString(T FromEnum)
{
return FromEnum.ToString();
}
public string ToString(IEnumerable<T> FromFlagsList)
{
return ToString(ToEnum(FromFlagsList));
}

public object ToUnderlyingType(T FromeEnum)
{
return Convert.ChangeType(FromeEnum , UnderlyingType);
}
}

用法:

 EnumConverter<ModifierKeys> conv = new EnumConverter<ModifierKeys>();
//conv.ToEnum
//conv.ToFlagsList
//conv.ToString

关于c# - 如何在(字符串、标志列表、带标志的枚举)之间转换枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38410350/

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