我在SharePoint Web部件中创建此选择框,并且需要使用当前版本进行下拉操作,因此我需要使用Enum。枚举中的数字常量(c#)
public enum SelectVersionEnum { 2010, 2007 };
那么你可以看到它打破了什么地方,有没有什么办法在枚举中使用整数? 最重要的是我想使用
public enum SelectVersionEnum { 2010=14, 2007=12 };
我在SharePoint Web部件中创建此选择框,并且需要使用当前版本进行下拉操作,因此我需要使用Enum。枚举中的数字常量(c#)
public enum SelectVersionEnum { 2010, 2007 };
那么你可以看到它打破了什么地方,有没有什么办法在枚举中使用整数? 最重要的是我想使用
public enum SelectVersionEnum { 2010=14, 2007=12 };
不,你不能用整数名称命名枚举。
枚举值名称是一个普通的标识符,必须遵循与其他所有规则相同的规则。
你可以,但是,使用:
public enum SelectVersionEnum
{
Version2007 = 12,
Version2010 = 14
}
此外,Enum.Parse
可以解析与整数字符串到其相应的枚举值,即使在字符串中描述的值不存在。
尝试在LINQPad如下:
void Main()
{
Enum.Parse(typeof(SelectVersionEnum), "12").Dump();
Enum.Parse(typeof(SelectVersionEnum), "14").Dump();
Enum.Parse(typeof(SelectVersionEnum), "2007").Dump();
}
public enum SelectVersionEnum
{
Version2007 = 12,
Version2010 = 14
}
输出:如果定义了以下
Version2007 Version2010 2007
你觉得会一直发生的事情:
public enum SelectVersionEnum
{
12 = 14,
14 = 16
}
请问字符串“14”现在的意思是“12”或“14”?
枚举成员必须是有效的C#标识符。
它们不能以数字开头。
取而代之,您可以使用类似Office2007, Office2010
或V2007, V2010
的东西。
不,枚举标识符不能以数字字符开头。
您可以像其他任何类型一样将扩展方法添加到您的枚举中。
所以,你可以为你的SelectVersionEnum的扩展,帮助您在正确的格式枚举值...
public static class SelectVersionEnumExtension
{
public static int Version(this SelectVersionEnum enumValue)
{
return 0; // Obviously you should return something meaningful here..
}
}
这给了你很多的flexibilty的。
一种方法可以使用与枚举关联的数值是使用description属性。例如,你可能有枚举:
[Serializable]
public enum SelectVersionEnum
{
[Description("2007")]
v2007,
[Description("2010")]
v2010
}
然后,您可以编写扩展方法来获取您正在寻找的数值。
public static string Description(this Enum value)
{
var type = value.GetType();
var name = Enum.GetName(type, value);
if (name != null)
{
if (type.GetField(name) != null)
{
var attr = Attribute.GetCustomAttribute(type.GetField(name), typeof(DescriptionAttribute)) as DescriptionAttribute;
return attr != null ? attr.Description : name;
}
}
return null;
} // end
你会使用这样的:
var version = SelectVersionEnum.v2007.Description();
下面的答案是正确的。花点时间考虑一下,即使C#允许这样做,这真是一个糟糕的主意和维护的噩梦。这是最终会发布到每日WTF的那种代码。 – 2011-03-14 14:26:53