gpt4 book ai didi

c# - 枚举中的 "&"?

转载 作者:太空宇宙 更新时间:2023-11-03 20:28:41 25 4
gpt4 key购买 nike

我想使用一些文件,我需要知道将每个数据放在哪里。一列称为“类别”。

我可以有很多类别,我想构建一个枚举来支持它们。

public enum GasKeyWords
{
Gas,
Fuel,
Gas&Fuel
}

public enum EducationKeyWord
{
Education,
Books&Supplies,
StudentLoan
Tuition
}

我在想这样的事

 foreach(var r in records)
{
Categories.GasKeyWords GasKeyWords;

bool valid = Enum.TryParse<Categories.GasKeyWords>(r, out GasKeyWords);

if (valid)
{
// add to group
}
}

并继续使用 TryParse,直到我找到一个它也可以解析的组。我不确定这是否是最好的方法(我总是乐于接受更好的想法)。

但是我现在面临的问题是我不能在枚举名称中使用“&”。我无法控制这些类别名称,因此无法更改。

最佳答案

为什么不使用 Description 标签来解决这个问题。当然,它并不完全是它的设计目的,但如果您对此有异议,那么您始终可以发明自己的属性类。

这是我为获取对象的描述属性而编写的一个快速的肮脏方法

    public static string GetDescription(this object enumeration)
{
//Again, not going to do your condition/error checking here.
//Normally I would have made this extension method for the Enum type
but you won't know the type at compile time when building the list of descriptions but ..
// you will know its an object so that is how I cheated around it.

var desc = enumeration.GetType().GetMember(enumeration.ToString())[0]
.GetCustomAttributes(typeof(DescriptionAttribute), true) as DescriptionAttribute[];

if (desc != null && desc.Length > 0)
{
return desc[0].Description;
}

return enumeration.ToString();
}

这是一个快速的肮脏实用方法,用于获取一个对象的所有描述符列表

public static IList<string> GetDescriptions<E>(E type)
{
//I'm not going to do your error checking for you.
//Figure out what you want to do in the event that this isn't an enumeration.
//Or design it to support different cases. =P

var list = new List<string>();
foreach(var name in Enum.GetNames(typeof(E)))
{
var enumObj = (E) Enum.Parse(typeof(E), name);
list.Add(enumObj.GetDescription());
}
return list;
}

现在利用这些达到你需要的效果

   public enum GasKeyWords
{
[Description("Gas")]
Gas,
[Description("Fuel")]
Fuel,
[Description("Gas&Fuel")]
GasFuel
}

...


var gasKeywords = Util.GetDescriptions<GasKeywords>();
foreach(var r in records)
{
var found = gasKeywords.Contains(r);
if (found)
{

}
}

我不是泛型大师。如果有人对如何解决 GetDescriptions() 方法的输入问题有一些想法,那将是受欢迎的。不幸的是,我无法设置期望 Enum 的类型约束,这使得它对编码不太友好。

关于c# - 枚举中的 "&"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8828511/

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