简体   繁体   中英

How to implement Global Strings C#

I have lots of global read only strings (around 100) that I am using in my application that will never change. I have been trying to think of the best solution that is easy to code and doesn't have too much impact on performance. I need the strings to be used throughout the application like the example below, where Relationship is just a category in which the value is grouped and Alternate is the string value itself.

Relationship.Alternate

I have thought of creating static classes with static read only fields, static classes with const fields, implementing a Singleton pattern and even creating and parsing enums in a helper method. Can anybody provide some good advice on the best way to tackle this problem.

How about using resource files ?

They are typed, easily accesible from your code at run-time, easily editable without need to recompile, and support any string content (ie not like enums, which only support identifier-like strings).

For example, you can add a resource file named GlobalStrings.resx to your C# project, and then add a string named Relationship_Alternate to that file. You can type any value you want for that string. In code, you would access the string value as:

GlobalStrings.Relationship_Alternate

Since those are identifiers validated at compile-time, you can guarantee that all your strings will load successfully at run-time.

Hope it helps.

为什么不将它们放在枚举中,这可以使其具有更高的存储效率,可读性以及更少的错误发生

if they are going to be set at compile time you can try putting them in appSettings (in your web.config or app.config). This would typically apply for connection strings etc. If they are going to be set at run time, depending on some other value, you can go with static class & static read only fields

Edit:If you want them strongly typed, you can also use settings file . see MSDN article

You should consider using a resource file. See MSDN or solution B in this CodeProject article .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM