csa*_*aam 7 c# const windows-8 windows-runtime
我创建了一个C#Windows Runtime组件,并且以下行:
public const bool LOG_ENABLED = false;
Run Code Online (Sandbox Code Playgroud)
抛出错误:
类型'常量'包含外部可见的常量字段'Constants.LOG_ENABLED'.常量只能出现在Windows运行时枚举中
这个错误是什么意思?我怎样才能声明常量?
这是一个老问题,但我会少给我两美分。const和public是危险的组合,经常会错过使用。这是由于以下事实:如果在库中更改了公共const字段,则不能仅替换库,而是需要重建该库的所有客户端,因为它将在客户端而不是引用中复制实际值。达到那个值。
一种选择是如果您确实想要一个公共的“常量”,则执行以下操作:
public static class Constants
{
public static readonly bool LOG_ENABLED = false;
}
Run Code Online (Sandbox Code Playgroud)
但是,这在WinRT组件库中也失败
“ WindowsRuntimeComponent1.Constants”包含外部可见字段“ System.Boolean WindowsRuntimeComponent1.Constants.LOG_ENABLED”。场只能通过结构暴露。
确实有效的另一种选择是
public static class Constants
{
public static bool LOG_ENABLED { get { return false; } }
}
Run Code Online (Sandbox Code Playgroud)
我不完全确定为什么在WinRT组件库中不可能有公共const或readonly,因为在普通的类库中有可能。
经过一番阅读后,似乎公共领域仅限于结构,而结构可能仅包含公共领域。
就像您在评论中说的那样,如果不从外部使用它,则将其更改为Internal是一个不错的选择。