39 c#
我想在我的枚举上设置空间.这是我的代码示例:
public enum category
{
goodBoy=1,
BadBoy
}
Run Code Online (Sandbox Code Playgroud)
我想设置
public enum category
{
Good Boy=1,
Bad Boy
}
Run Code Online (Sandbox Code Playgroud)
当我检索时,我想从枚举中看到Good Boy的结果
Luk*_*ien 54
您可以使用,修饰您的枚举值DataAnnotations
,因此以下情况属实:
using System.ComponentModel.DataAnnotations;
public enum Boys
{
[Display(Name="Good Body")]
GoodBoy,
[Display(Name="Bad Boy")]
BadBoy
}
Run Code Online (Sandbox Code Playgroud)
我不确定您为控件使用的UI框架,但是DataAnnotations
当您键入HTML.LabelFor
Razor视图时,ASP.NET MVC可以读取.
如果您不使用Razor视图或者您想要在代码中获取名称:
public class EnumExtention
{
public Dictionary<int, string> ToDictionary(Enum myEnum)
{
var myEnumType = myEnum.GetType();
var names = myEnumType.GetFields()
.Where(m => m.GetCustomAttribute<DisplayAttribute>() != null)
.Select(e => e.GetCustomAttribute<DisplayAttribute>().Name);
var values = Enum.GetValues(myEnumType).Cast<int>();
return names.Zip(values, (n, v) => new KeyValuePair<int, string>(v, n))
.ToDictionary(kv => kv.Key, kv => kv.Value);
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用它:
Boys.GoodBoy.ToDictionary()
Run Code Online (Sandbox Code Playgroud)
Sov*_*iut 19
你误解了枚举的用途.枚举用于编程目的,主要是给一个数字命名.这是为了程序员在阅读源代码时的好处.
status = StatusLevel.CRITICAL; // this is a lot easier to read...
status = 5; // ...than this
Run Code Online (Sandbox Code Playgroud)
枚举不用于显示目的,不应向最终用户显示.与任何其他变量一样,枚举不能在名称中使用空格.
要将内部值与可以向用户显示的"漂亮"标签相关联,可以使用字典或散列.
myDict["Bad Boy"] = "joe blow";
Run Code Online (Sandbox Code Playgroud)
Xti*_*n11 12
using System.ComponentModel;
Run Code Online (Sandbox Code Playgroud)
然后...
public enum category
{
[Description("Good Boy")]
goodboy,
[Description("Bad Boy")]
badboy
}
Run Code Online (Sandbox Code Playgroud)
解决了!!
根据Smac的建议,为了方便起见,我添加了一个扩展方法,因为我看到很多人仍然对此有问题。
我使用了注释和辅助扩展方法。
枚举定义:
internal enum TravelClass
{
[Description("Economy With Restrictions")]
EconomyWithRestrictions,
[Description("Economy Without Restrictions")]
EconomyWithoutRestrictions
}
Run Code Online (Sandbox Code Playgroud)
扩展类定义:
internal static class Extensions
{
public static string ToDescription(this Enum value)
{
FieldInfo field = value.GetType().GetField(value.ToString());
DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
}
Run Code Online (Sandbox Code Playgroud)
使用枚举的示例:
var enumValue = TravelClass.EconomyWithRestrictions;
string stringValue = enumValue.ToDescription();
Run Code Online (Sandbox Code Playgroud)
这将返回Economy With Restrictions
。
希望这可以帮助人们作为一个完整的例子。这个想法再次归功于Smac,我刚刚使用扩展方法完成了它。
归档时间: |
|
查看次数: |
67000 次 |
最近记录: |