相关疑难解决方法(0)

如何从价值中获取C#Enum描述?

可能重复:
获取Enum值的属性

我有一个带有Description属性的枚举,如下所示:

public enum MyEnum
{
    Name1 = 1,
    [Description("Here is another")]
    HereIsAnother = 2,
    [Description("Last one")]
    LastOne = 3
}
Run Code Online (Sandbox Code Playgroud)

我找到了一些用于根据Enum检索描述的代码

public static string GetEnumDescription(Enum value)
{
    FieldInfo fi = value.GetType().GetField(value.ToString());

    DescriptionAttribute[] attributes = fi.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];

    if (attributes != null && attributes.Any())
    {
        return attributes.First().Description;
    }

    return value.ToString();
}
Run Code Online (Sandbox Code Playgroud)

这允许我编写如下代码:

var myEnumDescriptions = from MyEnum n in Enum.GetValues(typeof(MyEnum))
                         select new { ID = (int)n, Name = Enumerations.GetEnumDescription(n) };
Run Code Online (Sandbox Code Playgroud)

我想要做的是,如果我知道枚举值(例如1) - 我该如何检索描述?换句话说,如何将整数转换为"枚举值"以传递给我的GetDescription方法?

c# enums

364
推荐指数
5
解决办法
41万
查看次数

将枚举与C#中的字符串相关联

我知道以下是不可能的,因为它必须是一个int

enum GroupTypes
{
    TheGroup = "OEM",
    TheOtherGroup = "CMB"
}
Run Code Online (Sandbox Code Playgroud)

从我的数据库中我得到一个包含不全面代码的字段(OEM和CMB).我想把这个领域变成一个枚举或其他可以理解的东西.因为目标是可读性,所以解决方案应该简洁.
我还有其他选择吗?

.net c#

298
推荐指数
15
解决办法
29万
查看次数

如何通过MVC剃刀代码获取Enum成员的显示名称属性?

我的模型中有一个名为"Promotion"的属性,它的类型是一个名为"UserPromotion"的标志枚举.我的枚举成员的显示属性设置如下:

[Flags]
public enum UserPromotion
{
    None = 0x0,

    [Display(Name = "Send Job Offers By Mail")]
    SendJobOffersByMail = 0x1,

    [Display(Name = "Send Job Offers By Sms")]
    SendJobOffersBySms = 0x2,

    [Display(Name = "Send Other Stuff By Sms")]
    SendPromotionalBySms = 0x4,

    [Display(Name = "Send Other Stuff By Mail")]
    SendPromotionalByMail = 0x8
}
Run Code Online (Sandbox Code Playgroud)

现在我希望能够在我的视图中创建一个ul来显示我的"Promotion"属性的选定值.这是我到目前为止所做的,但问题是如何在这里获取显示名称?

<ul>
    @foreach (int aPromotion in @Enum.GetValues(typeof(UserPromotion)))
    {
        var currentPromotion = (int)Model.JobSeeker.Promotion;
        if ((currentPromotion & aPromotion) == aPromotion)
        {
        <li>Here I don't know how to get the display attribute of …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc displayattribute razor

185
推荐指数
12
解决办法
23万
查看次数

我的枚举可以有友好的名字吗?

我有以下内容 enum

public enum myEnum
{
    ThisNameWorks, 
    This Name doesn't work
    Neither.does.this;
}
Run Code Online (Sandbox Code Playgroud)

enum带有"友好名字"的s 不可能吗?

c# enums

170
推荐指数
7
解决办法
15万
查看次数

标签 统计

c# ×4

enums ×2

.net ×1

asp.net-mvc ×1

displayattribute ×1

razor ×1