4

我正在使用Eto gui 框架。我在他们的源代码中看到了一些神奇的语法;例如:

int x;
int? x;
void func(int param);
void func(int? param);

有什么不同?我很困惑。而且这个符号?很难用谷歌搜索。

4

2 回答 2

8

这意味着它们是可空的,它们可以保存空值

如果您已定义:

int x;

那么你不能这样做:

x = null; // this will be an error. 

但如果您定义x为:

int? x;

那么你可以这样做:

x = null; 

Nullable<T> Structure

在 C# 和 Visual Basic 中,您可以使用 ? 将值类型标记为可为空的。值类型后的符号。例如,int? 用 C# 还是整数?在 Visual Basic 中声明了一个可以分配为 null 的整数值类型。

就我个人而言,我会使用http://www.SymbolHound.com来搜索符号,在这里查看结果

?只是语法糖,相当于:

int? xNullable<int> x

于 2013-02-26T05:45:57.937 回答
5

structs(如int,long等)默认不能接受null。因此,.NET 提供了一个struct名为type-paramNullable<T>的泛型T可以来自任何其他structs。

public struct Nullable<T> where T : struct {}

它提供了一个bool HasValue属性,指示当前Nullable<T>对象是否有值;和一个T Value获取当前Nullable<T>值的属性(如果是HasValue == true,否则它会抛出一个InvalidOperationException):

public struct Nullable<T> where T : struct {
    public bool HasValue {
        get { /* true if has a value, otherwise false */ }
    }
    public T Value {
        get {
            if(!HasValue)
                throw new InvalidOperationException();
            return /* returns the value */
        }
    }
}

最后,在回答您的问题时,TypeName?Nullable<TypeName>.

int? --> Nullable<int>
long? --> Nullable<long>
bool? --> Nullable<bool>
// and so on

并在使用中:

int a = null; // exception. structs -value types- cannot be null
int? a = null; // no problem 

例如,我们有一个在名为 的方法Table中生成 HTML 标记的类。看:<table>Write

public class Table {

    private readonly int? _width;

    public Table() {
        _width = null;
        // actually, we don't need to set _width to null
        // but to learning purposes we did.
    }

    public Table(int width) {
        _width = width;
    }

    public void Write(OurSampleHtmlWriter writer) {
        writer.Write("<table");
        // We have to check if our Nullable<T> variable has value, before using it:
        if(_width.HasValue)
            // if _width has value, we'll write it as a html attribute in table tag
            writer.WriteFormat(" style=\"width: {0}px;\">");
        else
            // otherwise, we just close the table tag
            writer.Write(">");
        writer.Write("</table>");
    }
}

上述类的用法 - 仅作为示例 - 如下所示:

var output = new OurSampleHtmlWriter(); // this is NOT a real class, just an example

var table1 = new Table();
table1.Write(output);

var table2 = new Table(500);
table2.Write(output);

我们将拥有:

// output1: <table></table>
// output2: <table style="width: 500px;"></table>
于 2013-02-26T05:57:50.240 回答