作为字符串或字符串常量的枚举
我遇到了 这个< /a> 博客文章,我只是好奇。我通常总是使用常量
作为我的应用程序中的共享字符串。
我想知道您认为前一种方式的优点/缺点是什么?
I came across this blog post and I was just curious. I usually always use constants
for my shared strings across my application.
I was wondering what you think the pros/cons of doing it the former way are though?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会坚持使用字符串常量,因为它们很简单并且不需要任何反射来获取值。
I would stick with string constants since they are straightforward and don't require any reflection to get the values.
该方法使用反射来提取字符串值。如果您正在做一些对性能至关重要的事情,请不惜一切代价避免这种情况...如果您想要速度,则常量是最佳选择。
更重要的是,通过使用那里的方法,您会严重伤害编译器优化器,因为每个“常量”现在都变成了“方法调用”。
The method there uses reflection to extract the string value. If you are doing something performance critical avoid this at all cost... constants are the way to go if you want speed.
More than that by using the method there you seriously hurt the compiler optimizer because each 'constant' now become a 'method call'.
这很大程度上取决于您存储的字符串类型。
如果它类似于向用户显示的文本,那么您首先就不应该使用常量。只读字段更好,资源也更好。
我在建议的解决方案中看到的主要缺点是它非常不直观:当我看到字符串常量或字段的使用时,我立即知道发生了什么。如果我看到
SomeEnum.SameValue.GetStringValue()
,我会认为它的作用与ToString()
的作用差不多,而不是一些有趣的事情。另外,像这样使用反射会慢得多,但这对你来说可能并不重要。
That largely depends on what kinds of string you're storing.
If it's something like text shown to users, then you shouldn't be using constants in the first place. Read-only fields are better and resources better yet.
The main disadvantage I can see in the proposed solution is that it's going to be very unintuitive: when I see usage of string constant or field, I immediately know what's going on. If I see
SomeEnum.SameValue.GetStringValue()
, I would assume it does pretty much whatToString()
would do, not some funny business.Also, using reflection like that is going to be much slower, but that might not matter to you.