我正在使用Eto gui框架.我在他们的源代码中看到了一些魔法语法; 例如:
int x;
int? x;
void func(int param);
void func(int? param);
Run Code Online (Sandbox Code Playgroud)
有什么不同?我很迷惑.而这个符号?
很难谷歌.
这意味着它们是Nullable,它们可以保存空值.
如果您已定义:
int x;
Run Code Online (Sandbox Code Playgroud)
那么你做不到:
x = null; // this will be an error.
Run Code Online (Sandbox Code Playgroud)
但如果你定义x
为:
int? x;
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
x = null;
Run Code Online (Sandbox Code Playgroud)
在C#和Visual Basic中,使用?将值类型标记为可为空?值类型后的表示法.例如,int?在C#或整数?在Visual Basic中声明一个可以指定为null的整数值类型.
我个人会用http://www.SymbolHound.com搜索符号,看看这里的结果
?
只是语法糖,它相当于:
int? x
和...一样 Nullable<int> x
struct
s(比如int
,long
等)null
默认不能接受.因此,.NET提供了一个通用struct
名称Nullable<T>
,T
type-param可以来自任何其他struct
s.
public struct Nullable<T> where T : struct {}
Run Code Online (Sandbox Code Playgroud)
它提供了一个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 */
}
}
}
Run Code Online (Sandbox Code Playgroud)
最后,回答你的问题,TypeName?
是一个捷径Nullable<TypeName>
.
int? --> Nullable<int>
long? --> Nullable<long>
bool? --> Nullable<bool>
// and so on
Run Code Online (Sandbox Code Playgroud)
并在使用中:
int a = null; // exception. structs -value types- cannot be null
int? a = null; // no problem
Run Code Online (Sandbox Code Playgroud)
例如,我们有一个在名为的方法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>");
}
}
Run Code Online (Sandbox Code Playgroud)
上述类的用法 - 仅作为示例 - 是这样的:
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);
Run Code Online (Sandbox Code Playgroud)
我们将:
// output1: <table></table>
// output2: <table style="width: 500px;"></table>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2020 次 |
最近记录: |