c# - 修饰符 'XXXX' 对此项目无效

标签 c# static

有谁知道我为什么会收到这些错误:

The modifier 'static' is not valid for this item

The modifier 'readonly' is not valid for this item

以下代码的第 3 行:

public class YYY
{
    private static readonly struct ZZZ
    {
        private int x = 0;
        private int y = 0;
        private int z = 0;
    }
}

当我研究这个问题时,我只找到了我不太了解的接口(interface)的答案,但我只想在我的类中创建一个静态只读结构字段。

最佳答案

staticreadonly 都是仅在对象的实现中使用的修饰符,而不是在定义中使用。当您声明要使用的 ZZZ 结构对象时,您可以添加修饰符 staticreadonly

public class YYY
{
    private struct ZZZ
    {
        private int x = 0;
        private int y = 0;
        private int z = 0;
    }

    private static readonly ZZZ myZZZ = new ZZZ(); //The declaration of a ZZZ instance.
}

关于c# - 修饰符 'XXXX' 对此项目无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15086940/

相关文章:

c# - 重命名 Blazor 项目中的默认文件夹

c# - (关于最佳实践的问题)为什么默认有 "using System.Text"?

java - 如何在graphstream中使用静态布局

c - C函数中的静态局部变量会影响执行速度吗?

C++静态成员函数错误C2556重载函数仅返回类型不同

c# - 如何在运行时更改OData EDM模型

javascript - 使用 knockout 将 List 绑定(bind)到 Viewmodel

c# - 建议在对象构造函数中添加事件

c - 错误 C4700 : uninitialized local variable "" used

java - 即使在应用程序关闭后,静态变量也会存在吗?