开发者

Generated constants for enum values

开发者 https://www.devze.com 2023-03-29 04:07 出处:网络
I\'d need to store some properties of the e开发者_JAVA百科num\'s entries in their constants. For example indicate whether a color is cold or warm.

I'd need to store some properties of the e开发者_JAVA百科num's entries in their constants. For example indicate whether a color is cold or warm.

enum Colors
{
  Yellow, // warm
  Blue,   // cold
  Gray,   // cold
  Red,    // warm
  // etc.
}

In C++ I would define a macro to generate bitmasks for the constants. Something like:

#define WARM 1
#define COLD 0

#define MAKECOLOR(index, type) ((index << 8) | type)

enum Colors
{
  Yellow = MAKECOLOR(0, WARM),
  Blue   = MAKECOLOR(1, COLD),
  Gray   = MAKECOLOR(2, COLD),
  Red    = MAKECOLOR(3, WARM),
  // etc.
}

In C# this is not possible because there are no macros. I want to avoid writing bitmask expressions directly in the enum. Like this:

  ...
  Gray   = ((2 << 8) | 0),
  ...

Any ideas?

P.S.

Yes, I'm a syntactic sugar freak. :D


You should use attributes at the enum values. Read this article, it's pretty good:

http://www.codeproject.com/KB/cs/enumwithdescription.aspx

Hope it helps!


I do tend to write the bit expression directly in the enum:

enum Colors
{
    Yellow = (0 << 8) | ColorTemp.Warm,
    Blue   = (1 << 8) | ColorTemp.Cold,
    Gray   = (2 << 8) | ColorTemp.Cold,
    Red    = (3 << 8) | ColorTemp.Warm,
}

enum ColorTemp
{
    Cold = 0,
    Warm = 1,
}

And then write a simple extension class at the bottom of the file, like this:

public static class ColorsExtensions
{
    public ColorTemp GetTemperature(this Colors color)
    {
        return (ColorTemp)(color & 0x01);
    }
}


In C#, enum need to have const values defined at compile-time. In sum, C# is more const than C++.

In C#, const is used to denote a compile-time constant expression. It'd be similar to this C++ code:

enum {
  count = buffer.Length;
}

Because buffer.Length is evaluated at runtime, it is not a constant expression, and so this would produce a compile error.

C# has a readonly keyword which is a bit more similar to C++'s const. (It's still much more limited though, and there is no such thing as const-correctness in C#).

const is meant to represent a compile-time constant... not just a read-only value.

You can't specify read-only but non-compile-time-constant local variables in C#, I'm afraid. Some local variables are inherently read-only - such as the iteration variable in a foreach loop and any variables declared in the first part of a using statement. However, you can't create your own read-only variables.

If you use const within a method, that effectively replaces any usage of that identifier with the compile-time constant value.

So, you are going to have to define your values at compile-time in your enum. They cannot be evaluated at run-time. Those are the rules.

0

精彩评论

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