0

有没有办法在 c# 中将变量声明为 Nullable?

struct MyStruct {        
    int _yer, _ner;

    public MyStruct() {

        _yer = Nullable<int>; //This does not work.
        _ner = 0;
    }
}
4

4 回答 4

5

_yer 必须声明为 int?或 Nullable<int>。

    int? _yer;
    int _ner;

    public MyStruct(int? ver, int ner) {

        _yer = ver;
        _ner = ner;
    }
}

或者像这样:

    Nullable<int> _yer;
    int _ner;

    public MyStruct(Nullable<int> ver, int ner) {

        _yer = ver;
        _ner = ner;
    }
}

请记住,结构不能包含显式的无参数构造函数。

error CS0568: Structs cannot contain explicit parameterless constructors
于 2008-10-15T11:02:50.733 回答
1

尝试像这样声明你的变量:

int? yer;
于 2008-10-15T11:02:21.607 回答
0

可空类型怎么样:

struct MyStruct
{
    private int? _yer, _ner;
    public MyStruct(int? yer, int? ner)
    {
        _yer = yer;
        _ner = ner;
    }
}
于 2008-10-15T11:02:31.547 回答
0

尝试最初将 _yer 声明为 Nullable 类型,而不是标准的 int。

于 2008-10-15T11:02:41.967 回答