2013-02-26 45 views
4

我正在使用Eto gui framework。我在他們的源代碼中看到了一些神奇的語法;例如: :什麼符號'?'類型名稱後的意思是

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

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

+0

可能重複爲什麼會出現一個關於私有變量定義的問號?](http://stackoverflow.com/questions/2326158/why-is-there-a-questionmark-on-the-private-variable-definition) – 2013-02-26 07:45:15

+0

可能的重複[C# - Basic問題:什麼是'?'?](http:// stackoverflo w_questions/2699373/c-sharp-basic-question-what-is) – 2013-02-28 22:43:06

回答

5

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

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類,在一個名爲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> 
的[
+1

+1但是..'value類型,將被存儲在堆棧中......' - 不是真的。參見:[該堆棧是實現細節,第一部分](http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx)作者Eric Lippert – Habib 2013-02-26 06:01:03

+0

@Habib謝謝。我很快就讀了。問候。 – 2013-02-26 06:06:40

8

這意味着他們是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與符號搜索,看看結果here

?只是語法糖,它等價於:

int? x是相同Nullable<int> x

相關問題