繁体   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