这是什么意思?运营商?

时间:2013-01-28 11:40:12

标签: c# operators

  

可能重复:
  C# using the question mark after a type, for example: int? myVariable; what is this used for?

我看到?运算符在很多地方使用过,并尝试使用Google和StackOverflow,但搜索引擎都将其从查询中排除,并且没有返回任何好的答案。

这个运营商的意义是什么?我通常在类型声明之后看到它:

int? x;
DateTime? t;

例如,int的以下两个声明之间有什么区别:

int? x;
// AND
int x;

7 个答案:

答案 0 :(得分:2)

此运算符不是运算符,而只是Nullable type的语法糖:

int? x;

相同
Nullable<int> x;

答案 1 :(得分:2)

您可以阅读:Nullable type -- Why we need Nullable types in programming language ?

int? x;//this defines nullable int x
x=null; //this is possible
// AND
int x; // this defines int variable
x=null;//this is not possible

答案 2 :(得分:1)

它不是运营商,但int?Nullable<int>的捷径。 Nullable<>是允许设置一些值类型变量null值的容器。

答案 3 :(得分:1)

它呼叫nullable types

  

Nullable类型是System.Nullable结构的实例。可空的   type可以表示其基础值的正常值范围   类型,加上一个额外的空值。

int? x;

相当于

Nullable<int> x;

答案 4 :(得分:1)

?运算符表示类型可以为空。 例如;

int? x = null; //works properly since x is nullable

int x = null; //NOT possible since x is NOT nullable

请注意,您访问变量值的方式会发生变化;

int? x = null; 
int y = 0;
if (x.HasValue)
{
    y = x.Value; // OK
}

y = x; //not possible since there is no direct conversion between types.

答案 5 :(得分:0)

差异b / w int?和int是int?可以存储null但int不能。

INT?被称为可空运算符,它基本上在使用数据库实体时使用。

更多信息 - http://msdn.microsoft.com/en-us/library/1t3y8s4s(v=vs.80).aspx

希望这会有所帮助!!

答案 6 :(得分:0)

该运算符使所有不可为空的对象可以为空。 所以这意味着你是否会声明一个变量int? x,它可以像这样分配: 诠释? x = null。如果没有?签名,你不能用空值赋值。

相关问题