开发者

Enums as strings or string constants

I came across this blog post and I was just curious. I usually always use constants for my shared string开发者_开发技巧s across my application.

I was wondering what you think the pros/cons of doing it the former way are though?


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'.


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 what ToString() would do, not some funny business.

Also, using reflection like that is going to be much slower, but that might not matter to you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜