1、可空类型修饰符(?)
引用类型可以使用空引用表示一个不存在的值,而值类型通常不能表示为空。
例如:string str=null; 是正确的,int i=null; 编译器就会报错。
为了使值类型也可为空,就可以使用可空类型,即用可空类型修饰符“?”来表示,表现形式为“T?”
例如:int? 表示可空的整形,DateTime? 表示可为空的时间。
T? 其实是System.Nullable(泛型结构)的缩写形式,也就意味着当你用到“T?”时编译器编译 时会把“T?”编译成 System.Nullable 的形式。
例如:int? ,编译后便是 System.Nullable 的形式。
(1)函数的返回类型是一个结构体(如StructA),而这个返回值有可能为空。
此时不能直接返回null或者0,否则编译器会报错:无法将null或者0隐式转成结构体StructA,因为它不是一种可以为null值的类型。
public struct StructA
{
...
}
public StructA GetStruct()
{
if(...)
{
return null;
}
else
{
StructA temp = new StructA();
return temp;
}
}
可以用:
public structA? GetStruct()
{
...
}
即在返回类型后面加“?”
原因:加一个问号表示一个可空对象,相当于 Nullable<StructA>
类型。
(2)对返回值进行判断:
structA? a = GetStruct();
if (a!=null)
{
...
}
else
{
//返回的结构体为空
}
例:
public Dictionary<string, TGameText> m_dicGameText = new Dictionary<string, TGameText>();
public struct TGameText
{
public string m_strKeyName;
public string m_strContext;
public bool m_bCanShow;
}
public TGameText? GetGameText(string key)
{
if (m_dicGameText.ContainsKey(key))
{
return m_dicGameText[key];
}
return null;
}
public void SetContext(string key, string context, bool canShow)
{
TGameText? currText = GetGameText(key);
if (currText != null)
{
if (currText.Value.m_strContext != context)
{
TGameText tempText = new TGameText();
tempText.m_strKeyName = key;
tempText.m_strContext = context;
tempText.m_bCanShow = canShow;
currText = tempText;
}
}
else
{
TGameText tempText = new TGameText();
tempText.m_strKeyName = key;
tempText.m_strContext = context;
tempText.m_bCanShow = canShow;
m_dicGameText.Add(key, tempText);
}
}
2. 三元(运算符)表达式( ? : )
例如:x ? y : z
表示如果表达式 x 为true,则返回 y;如果 x 为false,则返回 z,是省略 if { } else { } 的简单形式。
3. 空合并运算符( ?? )
用于定义可空类型和引用类型的默认值。如果此运算符的左操作数不为null,则此运算符将返回左操作数,否则返回右操作数。
例如:a ?? b
当 a 为 null 时则返回 b,a 不为 null 时则返回 a 本身。
空合并运算符为右结合运算符,即操作时从右向左进行组合的。如,a ?? b ?? c
的形式按a ?? ( b ?? c )
计算。