【发布时间】:2019-11-11 04:29:36
【问题描述】:
有一个简单的类:
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;
}
}
}
在这一行:
if (test != null)
叫
public static bool operator !=(Test test1, Test test2)
但在这一行:
t = test?.i;
没有调用任何重载的方法
如何重载运算符“?.”
【问题讨论】:
-
你认为运营商
?.在做什么?以及如何通过不同的实现来改变这种行为? -
stackoverflow.com/questions/349062/… 长话短说:空条件运算符不可重载。
-
原来Null-conditional不只是语法糖?
-
您的问题不清楚。你真的想超载
?.吗?或者你在问为什么你的==和!=重载没有被使用?这是两个非常不同的问题。前者的答案见标记的重复(它有一个不可重载运算符的半完整列表,以及相关文档的链接) -
@Peter Duniho 我需要,根据Test类内部变量的值,对象是否通过Null-conditional test
标签: c#