C# 符号';是什么';类型名称后的含义
我正在使用。我在他们的源代码中看到了一些神奇的语法; 例如:C# 符号';是什么';类型名称后的含义,c#,C#,我正在使用。我在他们的源代码中看到了一些神奇的语法; 例如: int x; int? x; void func(int param); void func(int? param); 有什么不同?我很困惑。 而且符号?很难用谷歌搜索。这意味着它们是,它们可以保存空值 如果您已定义: int x; 那么你不能做: x = null; // this will be an error. 但是如果您将x定义为: int? x; 然后你可以做: x = null; 在C#和visualba
int x;
int? x;
void func(int param);
void func(int? param);
有什么不同?我很困惑。
而且符号?
很难用谷歌搜索。这意味着它们是,它们可以保存空值
如果您已定义:
int x;
那么你不能做:
x = null; // this will be an error.
但是如果您将x
定义为:
int? x;
然后你可以做:
x = null;
在C#和visualbasic中,通过使用
这个值类型后的符号。例如,int?在C#或
整数?在VisualBasic中声明一个整数值类型,该类型可以
赋值为空
就我个人而言,我会用符号搜索,看看结果
?
只是语法上的糖分,相当于:
int?x
与可空xstruct
s(如int
,long
等)相同,默认情况下不能接受null
。因此,.NET提供了一个名为Nullable
的泛型struct
,T
类型参数可以来自任何其他struct
s
public struct Nullable<T> where T : struct {}
最后,在回答您的问题时,TypeName?
是Nullable
的快捷方式
例如,我们有一个表
类,它在名为Write
的方法中生成HTML
标记。见:
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>");
}
}
我们将有:
// output1: <table></table>
// output2: <table style="width: 500px;"></table>
//输出1:
//输出2:
+1但是..值类型和将存储在堆栈中…
-不太可能。参见:Eric Lippert可能的副本
int a = null; // exception. structs -value types- cannot be null
int? a = null; // no problem
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>