如何读取 ASP.Net 中的枚举值?
我的枚举结构是这样的
public enum UserRole
{
Administrator = "Administrator",
Simple_User = "Simple User",
Paid_User = "Paid User"
}
现在我想通过使用它的名称来读取这个枚举值假设
String str = UserRole.Simple_User;
它在str中给我“Simple User”而不是“Simple_User”
我们怎么能做到这一点???
My enum structure is this
public enum UserRole
{
Administrator = "Administrator",
Simple_User = "Simple User",
Paid_User = "Paid User"
}
Now i want to read this enum value by using its name suppose
String str = UserRole.Simple_User;
it gives me "Simple User" in str instead of "Simple_User"
How we can do this???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以像这样进行友好的描述:
并创建一个辅助函数:
并像这样使用它:
You can do a friendly description like so:
And make a helper function:
And use it like:
好吧,现在你知道枚举实际上是一个数字列表,你可以为它提供一个方便的字符串句柄:
另外,正如 @StriplingWarrior 所示,你可以通过获取枚举字符串名称并替换下划线等来走得更远。但是什么我认为你想要的是一种将一个好的人类字符串与每个值关联起来的方法。这个怎么样?
好吧,
System.ComponentModel
中可能有一些东西可以做到这一点 - 让我知道。我的解决方案的代码在这里:以及使之成为可能的时髦的 Enum 扩展:
因此,要获得人性化的值,您只需执行
ErrorCode.CTSTRPH.PrettyFormat()
Okay so by now you know that enum really is a list of numbers that you can give a handy string handle to like:
Also, as @StriplingWarrior showed, you can go so far by getting the enum string name and replacing underscores etc. But what I think you want is a way of associating a nice human string with each value. How about this?
Okay there's probably something in
System.ComponentModel
that does this - let me know. The code for my solution is here:And the funky Enum extension that makes it possible:
So to get the human-friendly value out you could just do
ErrorCode.CTSTRPH.PrettyFormat()
嗯,枚举不能有字符串值。来自 MSDN 的 Enum 页面:
要获取枚举的字符串版本,请使用 Enum 的 ToString 方法。
Hmm, enums can't have string values. From MSDN's Enum page:
To get the string version of the enum use the Enum's ToString method.
我对你的问题有点困惑,因为 C# 不允许你声明由字符串支持的枚举。您的意思是您想要获得“Simple User”,但您得到的却是“Simple_User”?
怎么样:
I'm a little confused by your question, because C# doesn't allow you to declare enums backed by strings. Do you mean that you want to get "Simple User", but you're getting "Simple_User" instead?
How about:
您可以通过属性来做到这一点,但实际上我认为使用这样的枚举可能是错误的处理方式。
我将创建一个公开显示名称属性的用户角色接口,然后为每个角色使用一个新类来实现该接口,这也让您将来可以添加更多行为。
或者您可以使用抽象类,这样任何通用行为都不会重复......
You can do this by attribute, but really I think using an enum like this is possibly the wrong way to go about things.
I would create a user role interface that exposes a display name property, then implement that interface with a new class for each role, this also let's you add more behaviour in the future.
Or you could use an abstract class so any generic behaviour doesn't get duplicated...