2013-02-26 105 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