将struct变量初始化为Nullable <int> </int>

时间:2008-10-15 11:00:23

标签: c# .net nullable

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

struct MyStruct {        
    int _yer, _ner;

    public MyStruct() {

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

4 个答案:

答案 0 :(得分:5)

_yer必须声明为int?或Nullable&lt; int&gt;。

    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

答案 1 :(得分:1)

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

int? yer;

答案 2 :(得分:0)

nullable types

怎么样?
struct MyStruct
{
    private int? _yer, _ner;
    public MyStruct(int? yer, int? ner)
    {
        _yer = yer;
        _ner = ner;
    }
}

答案 3 :(得分:0)

首先尝试将_yer声明为Nullable类型,而不是作为标准int。