gpt4 book ai didi

c# - WinRT 组件库中的公共(public)常量

转载 作者:太空狗 更新时间:2023-10-29 20:28:02 24 4
gpt4 key购买 nike

我创建了一个 C# Windows Runtime 组件,以及以下行:

public const bool LOG_ENABLED = false;

抛出错误:

类型“常量”包含外部可见常量字段“Constants.LOG_ENABLED”。常量只能出现在 Windows 运行时枚举中

这个错误是什么意思?我如何声明常量?

最佳答案

这是一个老问题,但我还是会给我两分钱。 const 和 public 是一个危险的组合,经常被误用。这是因为如果库中的公共(public) const 字段发生更改,则不能仅替换库,而是需要重建该库的所有客户端,因为它会复制客户端中的实际值而不是引用到那个值。

如果你真的想要一个公共(public)“常量”,一个选择是做这样的事情:

public static class Constants
{
public static readonly bool LOG_ENABLED = false;
}

但是这在 WinRT 组件库中也失败了

'WindowsRuntimeComponent1.Constants' contains externally visible field 'System.Boolean WindowsRuntimeComponent1.Constants.LOG_ENABLED'. Fields can be exposed only by structures.

另一种确实有效的选择是

public static class Constants
{
public static bool LOG_ENABLED { get { return false; } }
}

我不确定为什么不能在 WinRT 组件库中使用 public const 或 readonly,因为它可以在普通类库中使用。

经过一些阅读,公共(public)字段似乎仅限于结构,而结构可能只包含公共(public)字段。

正如您在评论中所说,如果您不从外部来源使用它,将其更改为内部是一个不错的选择。

关于c# - WinRT 组件库中的公共(public)常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13848645/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com