在这种情况下,为什么 "if-else" 与三元运算符“?:”的工作方式不同?
Why does "if-else" work differently from the ternary operator "?:" in this case?
正在声明 类
class A
{
public string a;
public static implicit operator A(B b) => new A() { a = b.b };
}
class B
{
public string b;
}
比较?:
和if-else
static public A Method1(B b)
{
return (b is null) ? null : b; //equally return b;
}
static public A Method2(B b)
{
if (b is null) return null; else return b;
}
方法1会抛出异常
方法 2 可以正常工作
Method1(null);
Method2(null);
为什么他们的行为不同?
在 Method1
中使用三元运算符时,return 值的类型在两个分支中必须相同(在您的情况下为 B
)。该值必须稍后转换为 A
以匹配方法的 return 类型。因此,隐式运算符中会抛出 NullReferenceException
(因为 b
为空)。
在 Method2
中,另一方面,您 returning null
直接 ;所以,不需要强制转换。
如果将 Method2
更改为如下内容,您会在 Method2
中得到相同的结果(即异常):
static public A Method2(B b)
{
B temp;
if (b is null) temp = null; else temp = b;
return temp; // Throws a NullReferenceException.
}
您应该做的是在隐式运算符中添加空检查:
public static implicit operator A(B b) => (b is null ? null : new A { a = b.b });
Method1
对于 return 值的三元运算符类型应该相等。
所以 null
实际上被 return 编辑为 (B)null
,然后使用隐式运算符转换为类型 A
Method2
直接将return值转换为(A)null
,不使用隐式运算符
Bonus
尝试将 Method1
的 return 类型更改为 B
,它应该可以工作。
public static B Method1(B b)
{
return (b is null) ? null : b;
}
正在声明 类
class A
{
public string a;
public static implicit operator A(B b) => new A() { a = b.b };
}
class B
{
public string b;
}
比较?:
和if-else
static public A Method1(B b)
{
return (b is null) ? null : b; //equally return b;
}
static public A Method2(B b)
{
if (b is null) return null; else return b;
}
方法1会抛出异常
方法 2 可以正常工作
Method1(null);
Method2(null);
为什么他们的行为不同?
在 Method1
中使用三元运算符时,return 值的类型在两个分支中必须相同(在您的情况下为 B
)。该值必须稍后转换为 A
以匹配方法的 return 类型。因此,隐式运算符中会抛出 NullReferenceException
(因为 b
为空)。
在 Method2
中,另一方面,您 returning null
直接 ;所以,不需要强制转换。
如果将 Method2
更改为如下内容,您会在 Method2
中得到相同的结果(即异常):
static public A Method2(B b)
{
B temp;
if (b is null) temp = null; else temp = b;
return temp; // Throws a NullReferenceException.
}
您应该做的是在隐式运算符中添加空检查:
public static implicit operator A(B b) => (b is null ? null : new A { a = b.b });
Method1
对于 return 值的三元运算符类型应该相等。
所以 null
实际上被 return 编辑为 (B)null
,然后使用隐式运算符转换为类型 A
Method2
直接将return值转换为(A)null
,不使用隐式运算符
Bonus
尝试将 Method1
的 return 类型更改为 B
,它应该可以工作。
public static B Method1(B b)
{
return (b is null) ? null : b;
}