相关疑难解决方法(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万
查看次数

如何通过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万
查看次数

C#vs Java Enum(适用于C#的新手)

我已经用Java编程了一段时间,只是投入了一个完全用C#编写的项目.我正试图加快C#的速度,并注意到在我的新项目中几个地方使用的枚举,但乍一看,C#的枚举似乎比Java 1.5+实现更简单.任何人都可以枚举C#和Java枚举之间的差异,以及如何克服这些差异?(我不想开始语言火焰战,我只想知道如何在C#中做一些我以前用Java做的事情).例如,有人可以发布一个C#对应的Sun着名的Planet枚举示例吗?

public enum Planet {
  MERCURY (3.303e+23, 2.4397e6),
  VENUS   (4.869e+24, 6.0518e6),
  EARTH   (5.976e+24, 6.37814e6),
  MARS    (6.421e+23, 3.3972e6),
  JUPITER (1.9e+27,   7.1492e7),
  SATURN  (5.688e+26, 6.0268e7),
  URANUS  (8.686e+25, 2.5559e7),
  NEPTUNE (1.024e+26, 2.4746e7),
  PLUTO   (1.27e+22,  1.137e6);

  private final double mass;   // in kilograms
  private final double radius; // in meters
  Planet(double mass, double radius) {
      this.mass = mass;
      this.radius = radius;
  }
  public double mass()   { return mass; }
  public double radius() { return radius; }

  // universal gravitational constant  (m3 kg-1 s-2) …
Run Code Online (Sandbox Code Playgroud)

c# java enums language-comparisons

172
推荐指数
6
解决办法
6万
查看次数

.NET - 如何将"大写"分隔的字符串拆分为数组?

我如何从这个字符串:"ThisIsMyCapsDelimitedString"

...到这个字符串:"这是我的帽子划分字符串"

VB.net中最少的代码行是首选,但C#也是受欢迎的.

干杯!

.net regex string algorithm pascalcasing

112
推荐指数
6
解决办法
2万
查看次数

如何获取枚举的自定义属性值?

我有一个枚举,每个成员都有一个自定义属性应用于它.如何检索存储在每个属性中的值?

现在我这样做:

var attributes = typeof ( EffectType ).GetCustomAttributes ( false );
foreach ( object attribute in attributes )
{
    GPUShaderAttribute attr = ( GPUShaderAttribute ) attribute;
    if ( attr != null )
        return attr.GPUShader;
}
return 0;
Run Code Online (Sandbox Code Playgroud)

另一个问题是,如果找不到,我应该返回什么?0是可以转换为任何枚举,对吧?这就是我回归的原因.

忘记提及,上面的代码为每个枚举成员返回0.

.net c# reflection custom-attributes

40
推荐指数
3
解决办法
4万
查看次数

访问自定义属性的值

我有这个自定义属性:

[AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited = true)]
class MethodTestingAttibute : Attribute
{   
    public string Value{ get; private set; }
    public MethodTestingAttibute (string value)
    {
        this.Value= value;

    }
}
Run Code Online (Sandbox Code Playgroud)

要像这样使用:

[MethodTestingAttibute("2")]
public int m1() {return 3; }
Run Code Online (Sandbox Code Playgroud)

而我的理念是采用MethodTestingAttibute的"2"值

object result = method.Invoke(obj, new Type[] {}); // here i get the return
Run Code Online (Sandbox Code Playgroud)

现在我想将此结果与Method TestingAttibute的值进行比较.我怎么能这样做?我试图走上这条路,但没有成功:method.GetCustomAttributes(typeof(MethodTestAttibute),true)[0] ...

什么是正确访问Custoum属性的字段?

c# attributes

22
推荐指数
2
解决办法
4万
查看次数

使用EnumMemberAttribute并执行自动字符串转换

我有以下代码

[DataContract]
public enum StatusType
{
    [EnumMember(Value = "A")]
    All,
    [EnumMember(Value = "I")]
    InProcess,
    [EnumMember(Value = "C")]
    Complete,
}
Run Code Online (Sandbox Code Playgroud)

我想做以下事情:

 var s = "C";
 StatusType status = SerializerHelper.ToEnum<StatusType>(s);   //status is now StatusType.Complete
 string newString = SerializerHelper.ToEnumString<StatusType>(status);   //newString is now "C"
Run Code Online (Sandbox Code Playgroud)

我已经使用DataContractSerializer完成了第二部分(参见下面的代码),但它似乎做了很多工作.

我错过了一些明显的东西吗 想法?谢谢.

    public static string ToEnumString<T>(T type)
    {
        string s;
        using (var ms = new MemoryStream())
        {
            var ser = new DataContractSerializer(typeof(T));
            ser.WriteObject(ms, type);
            ms.Position = 0;
            var sr = new StreamReader(ms);
            s = sr.ReadToEnd();
        }
        using (var xml …
Run Code Online (Sandbox Code Playgroud)

c# enums

20
推荐指数
3
解决办法
3万
查看次数

有人知道快速获取枚举值的自定义属性吗?

这可能是最好的例子.我有一个属性的枚举:

public enum MyEnum {

    [CustomInfo("This is a custom attrib")]
    None = 0,

    [CustomInfo("This is another attrib")]
    ValueA,

    [CustomInfo("This has an extra flag", AllowSomething = true)]
    ValueB,
}
Run Code Online (Sandbox Code Playgroud)

我想从实例中获取这些属性:

public CustomInfoAttribute GetInfo( MyEnum enumInput ) {

    Type typeOfEnum = enumInput.GetType(); //this will be typeof( MyEnum )

    //here is the problem, GetField takes a string
    // the .ToString() on enums is very slow
    FieldInfo fi = typeOfEnum.GetField( enumInput.ToString() );

    //get the attribute from the field
    return fi.GetCustomAttributes( typeof( CustomInfoAttribute  ), false …
Run Code Online (Sandbox Code Playgroud)

.net c# reflection enums attributes

18
推荐指数
2
解决办法
9031
查看次数

如何从VB.NET中的枚举中获取描述?

我有Enum如下

Public Enum FailureMessages
  <Description("Failed by bending")>
  FailedCode1 = 0

  <Description("Failed by shear force")>
  FailedCode2 = 1
End Enum
Run Code Online (Sandbox Code Playgroud)

每个枚举都有自己的描述.例如,FailedCode1有自己的描述为"弯曲失败".

下面是我的主要Sub(),我想将一个变量(类型字符串)分配给相应的枚举.

 Sub Main()
  Dim a As Integer = FailureMessages.FailedCode1
  Dim b As String 'I would b = Conresponding description of variable a above
  'that means: I would b will be "Failed by bending". How could I do that in .NET ?
 End Sub 
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮助我,我怎么能在VB.NET中做到这一点

.net vb.net string enums

8
推荐指数
1
解决办法
4335
查看次数

C#:Enum反模式

有人一直在谈论Enums一般违反清洁守则原则,所以我正在寻找人们最喜欢的Enum反模式和替代解决方案.

例如,我见过这样的代码:

switch(enumValue) {
    case myEnum.Value1:
        // ...
        break;
    case myEnum.Value2:
        // ...
        break;
}
Run Code Online (Sandbox Code Playgroud)

它比带有魔术字符串的switch语句更好一步,但这可能已经通过工厂,容器或其他模式更好地解决了.

甚至像这样的老派代码:

if(enumValue == myEnum.Value1) {
   // ...
} else if (enumValue == myEnum.Value2) {
   // ...
}
Run Code Online (Sandbox Code Playgroud)

您对枚举有哪些其他反模式和更好的实现

.net c# enums design-patterns anti-patterns

6
推荐指数
1
解决办法
4919
查看次数