可能重复:
获取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方法?
我的模型中有一个名为"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) 我已经用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) 我如何从这个字符串:"ThisIsMyCapsDelimitedString"
...到这个字符串:"这是我的帽子划分字符串"
VB.net中最少的代码行是首选,但C#也是受欢迎的.
干杯!
我有一个枚举,每个成员都有一个自定义属性应用于它.如何检索存储在每个属性中的值?
现在我这样做:
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.
我有这个自定义属性:
[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属性的字段?
我有以下代码
[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) 这可能是最好的例子.我有一个属性的枚举:
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) 我有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中做到这一点
有人一直在谈论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)
您对枚举有哪些其他反模式和更好的实现?
c# ×8
enums ×6
.net ×5
attributes ×2
reflection ×2
string ×2
algorithm ×1
asp.net-mvc ×1
java ×1
pascalcasing ×1
razor ×1
regex ×1
vb.net ×1