Moving constants to a separate assembly [closed]

情到浓时终转凉″ 提交于 2019-12-10 13:48:15

问题


I have a project which utilizes many global constants. Eventually I am planning to extract some parts of the program and create assemblies of its own.

Is it worthy (or is it possible?) to create an assembly for global constants alone (viz, GlobalConstants.dll), so that I can use this assembly in future assemblies?

This method will help me do less coding, and I can keep the same name for the constants across the projects.


回答1:


On how many projects do you expect the same constants to be useful? If there is genuinely a case for it, then fine; otherwise... don't.

Of course, if you have some equally likely to be reused utility library, then they might make sense in there, as long as appropriately scoped by namespace and type.

Personally, until I had an actual, concrete purpose in moving them, I'd leave them alone.




回答2:


While it is certainly possible to do and maybe even a pretty good idea, you should be aware of the fact that the C# compiler treats constants as values and not as references.

With this I mean that the C# compiler will replace all instances of the constant in you code and replace the "variable" with the value.

This means that even if you update the assembly GlobalConstants.dll and copy it to one of the applications you have, you will need to recompile that application. Not doing so, will cause the application to use the old constant values.

To overcome this problem, you can simply use public static readonly instead of public const as the readonly modifier differs from the const in that it is treated by the C# compiler as a reference in code rather than a value.




回答3:


One reason to create a separate constants assembly would be to allow "less complex" updates such as error messages and localizations where you can update the assembly as a hotfix and reduce the risk of breaking anything else.

Generally where we find sharing constants useful is having a business entity layer assembly which contains global constants - as business entities are the only layer in our arch. which can be accessed by (most) layers.

Having a separate assembly causes overheads, and depending on which constants you have, you may have some which are directly dependent on functionality - eg. a key which may be used to find a value in a Hashtable.



来源:https://stackoverflow.com/questions/5470929/moving-constants-to-a-separate-assembly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!