简体   繁体   English

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

[英]How to declare a compile time constant function in C#

In C++, we can use macro or constexpr (as C++11 said). 在C ++中,我们可以使用宏或constexpr(如C ++ 11所述)。 What can we do in C#? 在C#中我们可以做什么?

Please see "Cannot declare..." comment for context: 请参阅上下文的“无法声明...”注释:

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)
}

To declare a constant ( const ) the value assigned needs to be a compile time constant. 要声明一个常量( const ),分配的值必须是一个编译时间常量。 Calling a method automatically makes it not a compile time constant. 自动调用方法将使其不成为编译时间常数。

The alternative is to use static readonly : 替代方法是使用static readonly

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM