如何在 C# 中声明编译时常量函数

问题描述 投票:0回答:2

在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)
}
c# compilation constants constexpr
2个回答
6
投票

要声明常量 (

const
),分配的值需要是编译时常量。自动调用方法使其不再是编译时常量。

替代方法是使用

static readonly
:

public static readonly int SIZEOF_TEXUTRE_RGBA_U8C4_640x480_2 =
    4 * PixelType._8UC4.PixelSize() * 640 * 480;

0
投票

如果您迫切希望这样做,您可以使用 源生成器来完成。

源代码生成器可以在编译过程中生成包含您的常量的代码。然后,使用

partial
关键字,您可以将生成的代码和您编写的代码拼接在一起。

© www.soinside.com 2019 - 2024. All rights reserved.