gpt4 book ai didi

c# - 如何重载空条件运算符 "?."

转载 作者:行者123 更新时间:2023-12-03 18:36:48 24 4
gpt4 key购买 nike

有一个简单的类:

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;

没有一个重载方法被调用

如何重载运算符“?”

最佳答案

不,您不能重载 Null-conditional operators .查看 C# 列表 Overloadable operators .


附录 重载此运算符的能力实际上已向 C# 语言团队提出。见 Proposal: Allow null conditional (?.) and null coalescing ()?? operators to be overloadedProposal: nullable-like types .这些还没有被证实。

以下是我对这些和类似提案的担忧的理解:

更改这些运算符的语义可能会产生很多影响。例如,假设运算符是静态的,就可以说 null 的东西不是。这对于很多代码来说意味着很多问题。另一方面,您的代码可能在引用上挂起的时间过长或时间不够长,会导致垃圾回收出现问题。

即使可以解决这些和类似的问题,也不能掉以轻心。我们正在讨论现有代码的很多问题,这些代码已经部署在生产环境中。

关于c# - 如何重载空条件运算符 "?.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56820033/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com