有一个简单的类:
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
Test test = null;
int? t;
t = test?.i; // in this place the overloaded method "operator! =" is NOT called
if (test != null) // in this place the overloaded method "operator! =" is called
{
t = test.i;
}
}
}
public class Test
{
public int i = 5;
public override bool Equals(object obj)
{
return true;
}
public static bool operator ==(Test test1, Test test2)
{
return true;
}
public static bool operator !=(Test test1, Test test2)
{
return true;
}
}
}
Run Code Online (Sandbox Code Playgroud)
在这一行:
if (test != null)
Run Code Online (Sandbox Code Playgroud)
叫
public static bool operator !=(Test test1, Test test2)
Run Code Online (Sandbox Code Playgroud)
但在这一行:
t = test?.i;
Run Code Online (Sandbox Code Playgroud)
没有一个重载方法被调用
如何重载运算符“?”。
不,您不能重载Null条件运算符。请参阅C#重载运算符列表。
附录实际上已经向C#语言团队提出了重载此运算符的功能。请参阅提案:允许空条件(?。)和空合并()?? 建议重载的运算符和建议:可以为null的类型。这些尚未得到批准。
接下来是我对这些建议和类似建议的关注:
更改这些运算符的语义可能会有很多影响。例如,假设运算符是静态的,则可以说出不是的东西null。这对于很多代码来说意味着很多问题。另一方面,您可能会将代码挂在引用上的时间太长或不够长,这会带来垃圾回收问题。
即使可以解决这些问题和类似问题,也不应掉以轻心。我们正在谈论现有代码的许多问题,这些问题已经在生产环境中部署。