通常,问号主要用于条件句x ?“yes”:“no”。
但我看到过它的另一种用法,但找不到解释?例如,操作员。
public int? myProperty
{
get;
set;
}
通常,问号主要用于条件句x ?“yes”:“no”。
但我看到过它的另一种用法,但找不到解释?例如,操作员。
public int? myProperty
{
get;
set;
}
当前回答
In
x ? "yes" : "no"
的吗?声明一个if语句。这里:x表示布尔条件;在:之前的部分是then句,之后的部分是else句。
例如,
int?
的吗?声明一个可空类型,并意味着它前面的类型可能有一个空值。
其他回答
它声明该类型是可空的。
为了补充上面的答案,这里有一个代码示例
struct Test
{
int something;
}
struct NullableTest
{
int something;
}
class Example
{
public void Demo()
{
Test t = new Test();
t = null;
NullableTest? t2 = new NullableTest();
t2 = null;
}
}
这将给出一个编译错误:
错误12不能将null转换为“Test”,因为它是非空的 值类型
注意NullableTest没有编译错误。(注意?在t2的声明中)
它是Nullable<int>的缩写。Nullable<T>用于允许将值类型设置为null。值类型通常不能为空。
表示用(int?)声明的变量是可空的
int i1=1; //ok
int i2=null; //not ok
int? i3=1; //ok
int? i4=null; //ok
这意味着所讨论的值类型是可空类型
Nullable types are instances of the System.Nullable struct. A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, a Nullable<Int32>, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A Nullable<bool> can be assigned the values true, false, or null. The ability to assign null to numeric and Boolean types is especially useful when you are dealing with databases and other data types that contain elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined. class NullableExample { static void Main() { int? num = null; // Is the HasValue property true? if (num.HasValue) { System.Console.WriteLine("num = " + num.Value); } else { System.Console.WriteLine("num = Null"); } // y is set to zero int y = num.GetValueOrDefault(); // num.Value throws an InvalidOperationException if num.HasValue is false try { y = num.Value; } catch (System.InvalidOperationException e) { System.Console.WriteLine(e.Message); } } }