【问题标题】:How to declare a compile time constant function in C#如何在 C# 中声明编译时常量函数
【发布时间】:2013-04-22 09:39:35
【问题描述】:

在 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# 是否与 C++11 中的 constexpr 等效的方法吗?

标签: c# compilation constants constexpr


【解决方案1】:

要声明一个常量 (const),分配的值必须是编译时常量。自动调用方法使其不是编译时间常数。

替代方法是使用static readonly:

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

【讨论】:

  • 我必须将 SIZEOF_TEXUTRE_RGBA_U8C4_640x480_2 设为“const”,因为未来代码需要编译时间常数...“只读”广播运行时间取决于...这是 C# 语言限制 - 无法声明编译时间常数函数?有什么解决办法吗?
  • @Raymond:为什么未来的代码需要编译时间常数?
  • @Raymond:我感觉你并不真正理解 compile time constant 的真正含义。这意味着编译器知道该值。这进一步意味着常量声明将从生成的 IL 代码中完全消失,因为无论在何处使用常量的值都是内联的。 C#编译器不执行它当前正在编译的程序的代码,所以不可能将方法声明为编译时间常数。
  • 我清除了编译时间的含义,但我确实想在我的示例代码中简化“const”声明。 SIZEOF_TEXUTRE_RGBA_U8C4_640x480_2 只是从其他常量计算出来的常量。 “计算公式”很简单。我想“重用”这个公式。
  • @Raymond:你不能。 C# 中没有预处理器,也不支持真正的template metaprogramming
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-25
  • 2020-06-06
  • 1970-01-01
  • 2011-06-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多