在Java中,我们可以像这样声明enums
public enum ChangeFlag
{
NEW("New"),
DELETED("Deleted"),
REVISED("Revised");
private final String text;
ChangeFlag(String text)
{
this.text = text;
}
public String toString()
{
return text;
}
}
对于C#,有没有优雅的等价物?
编辑:
public static class FooExtensions
{
public static string GetDescription(this Foo @this)
{
switch (@this)
{
case Foo.Bar:
return "A bar";
}
}
}
你能解释一下GetDescription(这个Foo @this)中的参数是什么意思吗?
我不习惯看到this Foo @this
指的是什么
答案 0 :(得分:5)
您可以使用DescriptionAttribute
:
public enum Foo
{
[Description("A bar")]
Bar
}
然后您可以通过TypeDescriptor.GetAttributes
或Type.GetCustomAttributes
提取。
或者你可以使用扩展方法:
public enum Foo
{
Bar
}
public static class FooExtensions
{
public static string GetDescription(this Foo @this)
{
switch (@this)
{
case Foo.Bar:
return "A bar";
}
}
}
// consuming code
var foo = Foo.Bar;
var description = foo.GetDescription();
后一种方法在本地化方面也为您提供了更多控制,因为您总是可以在资源文件中查找描述。例如。
答案 1 :(得分:2)
internal static class Program
{
private static void Main(string[] args)
{
ChangeFlag changeFlag = ChangeFlag.REVISED;
Console.WriteLine(changeFlag.GetDescription());
Console.Read();
}
public enum ChangeFlag
{
[Description("New")]
NEW,
[Description("Deleted")]
DELETED,
[Description("Revised")]
REVISED
}
}
public static class EnumExtensions
{
public static string GetDescription(this Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
if (fi != null)
{
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
}
return value.ToString();
}
}
答案 2 :(得分:2)
枚举描述getter扩展方法的紧凑且防错的实现变体:
/// <exception cref="AmbiguousMatchException">More attributes found. </exception>
/// <exception cref="TypeLoadException">Cannot load custom attribute.</exception>
public static string GetDescription(this Enum value)
{
Type type = value.GetType();
string enumName = Enum.GetName(type, value);
if (enumName == null)
{
return null; // or return string.Empty;
}
FieldInfo typeField = type.GetField(enumName);
if (typeField == null)
{
return null; // or return string.Empty;
}
var attribute = Attribute.GetCustomAttribute(typeField, typeof(DescriptionAttribute));
return (attribute as DescriptionAttribute)?.Description; // ?? string.Empty maybe added
}
同样,描述的比较扩展方法(使用鞋帮)可能很有用:
public static bool DescriptionEquals(this Enum value, string inputForComparison,
StringComparison comparisonType = StringComparison.InvariantCultureIgnoreCase)
{
string description;
try
{
description = value.GetDescription();
}
catch (Exception ex) when (ex is AmbiguousMatchException || ex is TypeLoadException)
{
return false;
}
if (description == null || inputForComparison == null)
{
return false;
}
return inputForComparison.Equals(description, comparisonType);
// || inputForComparison.Equals(value.ToString(), comparisonType); may be added
}