在C#中以T形式返回枚举值



我正试图用一个以Type enumType为参数并返回IDictionary<T, string>的泛型类型T实现一个泛型方法。

基本上,我想返回一个字典,将枚举的所有值与自定义标签配对。例如,假设我有以下枚举:

public enum SOEnum
{
FirstVal,
SecondVal,
ThirdVal,
}
public enum FooEnum
{
Abc = 1,
Def = 2,
Ghi = 4
}
public enum BarEnum
{
Pippo = 'Pippo',
Pluto = 'Pluto'
}

根据传递的参数,我想获得一个这样的字典:

// In case the input is SOEnum.GetType() //
var dictionary = new Dictionary<SOEnum, string>()
{
{ SOEnum.FirstVal, "This is the first Value" },
{ SoEnum.SecondVal, "What a wonderful new" },
{ SOEnum.ThirdVal, "That's ok" }
}
// In case the input is FooEnum.GetType() //
var dictionary = new Dictionary<FooEnum, string>()
{
{ FooEnum.Abc, "Label 1" },
{ FooEnum.Def, "Label 2" },
{ FooEnum.Ghi, "Label 3" }
}
// In case the input is BarEnum.GetType() //
var dictionary = new Dictionary<BarEnum, string>()
{
{ BarEnum.Pippo, "Label of Pippo" },
{ BarEnum.Pluto, "Label of Pluto" },
}

请注意,我不想在枚举中放置标签,因为枚举可能已经具有int关联。

无论如何,我想到了这样的事情:

public override IDictionary<T, string> GetEnumLabels<T>(Type enumType)
{
if (!typeof(T).IsEnum || !enumType.IsEnum)
throw new ArgumentException("T must be an enumerated type");
if (enumType == typeof(SOEnum) && typeof(T) == typeof(SOEnum))
{
return new Dictionary<T, string>()
{
{(T)SOEnum.FirstVal, "This is the first Value" },
{(T)SOEnum.SecondVal, "What a wonderful new" },
{(T)SOEnum.ThirdVal, "That's ok"}
};
}
else if (enumType == typeof(FooEnum) && typeof(T) == typeof(FooEnum))
{
return new Dictionary<T, string>()
{
{ (T)FooEnum.Abc, "Label 1" },
{ (T)FooEnum.Def, "Label 2" },
{ (T)FooEnum.Ghi, "Label 3" }
};
}
else if (enumType == typeof(BarEnum) && typeof(T) == typeof(BarEnum))
{
return new Dictionary<T, string>()
{
{ (T)BarEnum.Pippo, "Label of Pippo" },
{ (T)BarEnum.Pluto, "Label of Pluto" },
};
}

return null;
}

但问题是,我无法像那样从任何枚举转换为T

无需使用泛型方法,因为它仅限于枚举。

你应该把属性放在每个枚举上,比如这个

public enum FooEnum
{
[Display(Name = "This is the first Value")]
OneVal,
}
public enum BarEnum
{
[Display(Name = "This is X Value")]
XVal,
}

然后每当你想得到显示值

public static string GetDisplayName(this Enum enumValue)
{
var attr = enumValue.GetType()
.GetMember(enumValue.ToString())
.First()
.GetCustomAttribute<DisplayAttribute>();
if (attr == null)
{
throw new NotImplementedException("enum has no display attribute");
}
return attr.Name;
}

最新更新