由于枚举使用整数,我可以用什么样的结构,给我挂的名称值枚举类访问:枚举与字符串以外的返回类型?
[我知道这是不对的,寻找替代]
private enum Project
{
Cleanup = new Guid("2ED3164-BB48-499B-86C4-A2B1114BF1"),
Maintenance = new Guid("39D31D4-28EC-4832-827B-A11129EB2"),
Upgrade = new Guid("892F865-E38D-46D7-809A-49510111C1"),
Sales = new Guid("A5690E7-1111-4AFB-B44D-1DF3AD66D435"),
Replacement = new Guid("11E5CBA2-EDDE-4ECA-BDFD-63BDBA725C8C"),
Modem = new Guid("6F686C73-504B-111-9A0B-850C26FDB25F"),
Audit = new Guid("30558C7-66D9-4189-9BD9-2B87D11190"),
Queries = new Guid("9985242-516A-4151-B7DD-851112F562")
}
编辑2014年7月20日
这是一个较新的回答这个问题。使用Attribute类和辅助方法,定义您的枚举所需的额外属性。
public enum MultiValueEnum
{
[FooAttribute("alpha", 20d, true)]
First,
[FooAttribute("beta", 40.91d, false)]
Second,
[FooAttribute("gamma", 1.2d, false)]
Third,
}
public class FooAttribute : Attribute
{
internal FooAttribute(string name, double percentage, bool isGood)
{
this.Name = name;
this.Percentage = (decimal)percentage;
this.IsGood = isGood;
}
public string Name { get; private set; }
public decimal Percentage { get; private set; }
public bool IsGood { get; private set; }
}
public static TAttribute GetAttribute<TAttribute>(this Enum value)
where TAttribute : Attribute
{
var type = value.GetType();
var name = Enum.GetName(type, value);
return type.GetField(name)
.GetCustomAttributes(false)
.OfType<TAttribute>()
.SingleOrDefault();
}
这使得它如此简单:
MultiValueEnum enumVar = MultiValueEnum.First;
var enumStringValue = enumVar.GetAttribute<FooAttribute>().Name;
var enumValueDecimal = enumVar.GetAttribute<FooAttribute>().Percentage;
var enumBool = enumVar.GetAttribute<FooAttribute>().IsGood;
无法访问结构中的专用字段,也无法像在结构中那样初始化字段。 – leppie 2009-07-08 11:01:28
他们需要也是静态的,例如工作。 – leppie 2009-07-08 11:02:09
你不应该能够创建这个结构体的实例,因为它只能作为一个容器来使用 – 2009-07-08 11:05:03