枚举中的数字常量(c#) [英] Numeric constants in enum (c#)

查看:133
本文介绍了枚举中的数字常量(c#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在SharePoint Web部件中创建此选择框,需要使用当前版本进行下拉列表,因此我需要使用枚举。

  public enum SelectVersionEnum {2010,2007}; 

你可以看到它在哪里打破,有没有办法在枚举中使用整数?
我最想使用的最重要的是/ $ p $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $


解决方案

不,您不能使用整数名称命名枚举。



枚举值名称是一个正常的标识符,必须遵循与其他内容相同的规则。



您可以但是,请使用:

  public enum SelectVersionEnum 
{
Version2007 = 12,
版本2010 = 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?


I'm creating this selectbox in a SharePoint web part and need to have a drop down with the current version so I need to use an Enum.

public enum SelectVersionEnum { 2010, 2007 };

Well you can see where it breaks, is there any way to use integers in a enum? Most of all I'd like to use

public enum SelectVersionEnum { 2010=14, 2007=12 };

解决方案

No, you can not name enums with integer names.

An enum value name is a normal identifier and must follow the same rules as everything else.

You can, however, use:

public enum SelectVersionEnum
{
    Version2007 = 12,
    Version2010 = 14
}

Additionally, Enum.Parse can parse strings with integers into their corresponding enum value, even if value described in the string doesn't exist.

Try the following in 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
}

The output:

Version2007
Version2010
2007

What do you think would've happened if you defined the following:

public enum SelectVersionEnum
{
    12 = 14,
    14 = 16
}

Does the string "14" now mean "12" or "14"?

这篇关于枚举中的数字常量(c#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆