开发者

My implementation of global CONSTs - is it possible to do something differently?

I'm a professional php programmer and lately I started a project in C#. These are my first steps with C#.

For one of my solutions I would like to use global CONSTs. I'm aware that C# doesn't allow you to define any variable outside a class scope, but I would like to try and implement something like it anyway, even just for the purpose of learning different techniques in the language.

I see the best way to do something similar global CONSTs is to define a static class, let's call it Const, that will hold my all of my solution's 'constants'. The class will use a private dictionary to hold the values, a method called 'define()' to set a value in this dictionar, 'is_defined()' to check if a const exists etc..

Now I'm about to write the method that will return the value. Obviously I could use a method Const.GetConst('someConstName') and get the wanted value, but that's a long way to retrieve a const anytime I need it. I though of using something like PHP's magic getter (if you're not familiar with it - you define inside a class a method called '__get' which handles all requests for a variable inside the class which is not defined). However, I couldn't find anything similar in C#. The closest thing I could find is a way to dynamically create a method inside a class in runtime, so that everytime a CONST will be created in my class, I'll create a "get method" that will pull the value from the private dictionary (this is开发者_开发知识库 not a get method in the classic form because is won't return a variable, instead, it will look for a value in a dictionary and return it).

Basically, what I'm asking is - - Is there any way to define global consts? - (even id the answer to the previous question is yes) Is there a way to set a better getter for dynamically define variables?

Thank you very much for the help


C# certainly allows you to declare public constants, Math.Pi would be a good example. It is however almost always the wrong thing to do. The problem is that constant values are directly compiled into the IL. That makes them very efficient, no memory access is required to lookup their value, but also very dangerous when you make the public.

What goes wrong is deploying updates for the assembly that contains the const declaration. You can alter the value but other assemblies that also use the constant are still using the old value. Embedded firmly in their IL. This will not come to a good end.

Public constants are only suitable for manifest constants. Like Math.Pi, it takes a drastic change in the way the Universe works to ever change that value. Something like a company or product name is already suspect, names change all the time without a programmer getting involved in the decision.

Use the readonly keyword for public constant values.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜