转换 C# 枚举的更简洁方法
我想使用一个对象(由框架返回,不在我的控制范围内),myField
,它具有枚举SPNumberFormatTypes
类型的属性DisplayFormat
。
我想将 DisplayFormat 的整数值作为字符串分配给XmlAttribute
。这是我目前所做的:
myAttribute.Value = ((Int32)((SPNumberFormatTypes)field.DisplayFormat)).ToString();
实现这一目标的另一种可能的方法是:
myAttribute.Value = ((Int32)Enum.Parse(typeof(SPNumberFormatTypes), field.DisplayFormat.ToString())).ToString();
我想知道是否有一种更简单/更干净的方法来实现这一目标?
I want to use an object (returned by framework, not in my control), myField
which has a property DisplayFormat
of type enum SPNumberFormatTypes
.
I want to assign the integer value of DisplayFormat as a string to an XmlAttribute
. Here is what I currently do:
myAttribute.Value = ((Int32)((SPNumberFormatTypes)field.DisplayFormat)).ToString();
One more possible way to achieve this is:
myAttribute.Value = ((Int32)Enum.Parse(typeof(SPNumberFormatTypes), field.DisplayFormat.ToString())).ToString();
I want to know if there is a simpler/cleaner way to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,将您所拥有的内容重构为扩展方法,例如
ValueToString
:用法:
此外,
enum
的名称应该是单数,因此SPNumberFormatType
。对于enum
的每个成员,例如Foo
,SPNumberFormatType.Foo
是一种格式类型,而不是一种格式类型。这就是为什么它应该是单一的。但是,如果SPNumberFormatTypes
被标记为Flags
那么你就可以了,复数是标准的,但你应该将DisplayFormat
重命名为DisplayFormats< /代码>。
以下是来自 MSDN 的命名指南。
Yes, refactor what you have into an extension method, say,
ValueToString
:Usage:
Also, the name of your
enum
should be singular soSPNumberFormatType
. For each member of yourenum
, sayFoo
,SPNumberFormatType.Foo
is a format type, not a format types. This is why it should be singular. If, however,SPNumberFormatTypes
is marked asFlags
then you're fine, plural is standard but you should renameDisplayFormat
toDisplayFormats
.Here are the naming guidelines from MSDN.
@itowlson 的评论是正确的答案。由于枚举已经是 SPNumberFormatTypes 类型,因此无需将其强制转换为该类型。因此,我的目标可以通过这样做以更简单的方式实现:
谢谢@itowlson!
@itowlson's comment is the correct answer. Since the enum is already of type SPNumberFormatTypes, there is no need to cast it to that type. Thus my objective can be acheived in an easier way by doing this:
Thanks @itowlson!
扩展方法怎么样?
http://msdn.microsoft.com/en-us/library/bb383977。 ASPX
How about an extension method?
http://msdn.microsoft.com/en-us/library/bb383977.aspx