Ray*_*ond 2 c# compilation const constexpr
在C++中,我们可以使用宏或constexpr(如C++ 11所述).我们在C#中可以做些什么?
有关上下文,请参阅"无法声明..."注释:
static class Constant
{
// we must ensure this is compile time const, have to calculate it from ground...
public const int SIZEOF_TEXUTRE_RGBA_U8C4_640x480 = 4 * sizeof(byte) * 640 * 480;
// Cannot declare compile time constant as following in C#
//public const int SIZEOF_TEXUTRE_RGBA_U8C4_640x480_2 = 4 * PixelType._8UC4.PixelSize() * 640 * 480;
}
public static class PixelTypeMethods
{
public static /*constexpr*/ int PixelSize(this PixelType type)
{
int value = (int)type;
int unit_size = value & 0xFF;
int unit_count = (value & 0xFF00) >> 8;
return unit_count * unit_size;
}
}
[Flags]
public enum PixelType
{
RGBA_8UC4 = RGBA | _8U | _C4,
/////////////////////////
RGBA = 1 << 16,
/////////////////////////
_8UC4 = _8U | _C4,
/////////////////////////
_C4 = 4 << 8,
/////////////////////////
_8U = sizeof(byte)
}
Run Code Online (Sandbox Code Playgroud)
要声明一个constant(const),赋值必须是一个编译时常量.自动调用方法使其不是编译时常量.
另一种方法是使用static readonly:
public static readonly int SIZEOF_TEXUTRE_RGBA_U8C4_640x480_2 =
4 * PixelType._8UC4.PixelSize() * 640 * 480;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4893 次 |
| 最近记录: |