簡體   English   中英

什么是符號'?' 在類型名稱之后

[英]what does symbol '?' after type name mean

我正在使用Eto gui框架 我在他們的源代碼中看到了一些魔法語法; 例如:

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

有什么不同? 我很困惑。 和符號? 很難谷歌。

這意味着它們是Nullable它們可以保存空值

如果您已定義:

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? x int? xNullable<int> x

struct s(如intlong等)默認情況下不能接受null 因此,.NET提供了一個名為Nullable<T>的通用structT類型參數可以來自任何其他struct

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

它提供了一個bool HasValue屬性,指示當前Nullable<T>對象是否具有值; 和一個獲取當前Nullable<T>值的T Value屬性(如果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類,它在名為Write的方法中生成HTML <table>標記。 看到:

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM