我可以在 .net 中获得类似枚举的字符串功能吗?
我正在尝试想出一种方法来保留要在我的项目中使用的字符串列表。
假设我有一个网站列表:
www.website1.com
www.website2.com
www.website3.com
www.website4.com
我希望我能得到一些类似于枚举与整数的工作方式的东西。
当有人需要检查网址时,他们将有一个可供选择的列表,并且能够编写类似这样的内容,也许
WebsiteNames.Website1
有一个好的(干净的)方法可以做到这一点?
I'm trying to come up with a way to keep a list of strings to be used within my project.
So lets say I have a list of websites:
www.website1.com
www.website2.com
www.website3.com
www.website4.com
I was hoping I could get something working similar to how enums work with ints.
When someone needs to check the url they will have a list they can choose from and would be able to write something like this maybe
WebsiteNames.Website1
Is there a good(clean) way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
像这样的类应该这样做:
如果一个字段是公开暴露的,通常最好将其设置为静态只读而不是 const,因为字符串值的任何更改都需要重新编译所有依赖模块才能获得更改。
A class like so should do it:
If a field is publicly exposed it's generally best to make it static readonly rather than const, since any change in the value of the string would require all dependent modules to be re-compiled to get the change.
您可以这样使用
struct
:由于
struct
是一种值类型
,因此它的用法类似于enum
。You can use the
struct
like this:Since
struct
is avalue type
, its usage is similar toenums
.您可以像这样使用静态类:
然后您可以像这样使用它:
如果您查看 T4 您甚至可以自动生成这样的文件,这样您就不必担心手动编写它或如果有人更改代码中的某些内容或运行时错误。
You can use a static class like this:
Then you can use it like:
If you have a look at T4 you could even generate a file like this automatically so you won't have to worrie about writing it by hand or runtime errors if someone changes something in the code.