开发者

How to share constant values in .net namespaces?

I'm trying to port some code into .net which has a load of #define'd values e.g.

#define MY_CONSTANT       (512)
#define MY_VERSION_STRING "v42.2"

When I import a cli library the #define's are lost. Is there a way of defining constants in the scope of a namespace. I was thinking something like this:

namespace MyNamespace
{
    const int MY_CONSTANT = 512;
    const String^ MY_VERSION_STRING = "v42.2";
}

So in future I could refer to that as:

int myVar = MyNamespace::MY_CONSTANT;
String^ myVar = MyNamespace::MY开发者_如何学编程_VERSION_STRING;

[Edit] Some of the constants are strings so an enum won't solve the general case.

[Edit2] I'm using C++/CLI here and right now interoperability with other .net languages is not a priority. That said, if there's a more .net-like way of solving this (i.e. standard practice) I'd rather go with that.


You can define a static class holding public fields that work as constants, eg.

namespace MyNamespace
{
    public class Constants
    { 
        public static int MyConstant1 { get { return 512; } }
        public static int MyConstant2 { get { return 1024; } }
    }
}

Then you can use Constants.MyConstant1 in place of MY_CONSTANT.

Note, though, that having a 'general' constants class is a 'bad practice': the kosher way is to keep related constants in the class related to what they define, eg. if you have a FileParser class that uses a MaxBufferSize constant, you would define a static FileParser.MaxBufferSize constant.


If there are multiple related values, it's usually better to do this with enums. Otherwise, hang them off a class, like:

public static class ConstantStuff
{
   public const int MyConstant = 512;
   public const int SomethingElse = 42;
}

C# doesn't allow "naked" constants.


I believe that if you put them at namespace scope they may not be accessible to C# apps, if that's important to you - best to wrap them in a ref class.


You cannot declare constants inside namespaces. You need to define a container to put your consts into, like a class, struct or enum.

public static class MyConstants
{
    public const float ConstantValue1 = 0;
}

and refer to them like this:

float value = MyConstants.ConstantValue1 ;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜