【问题标题】:How to overload Null-conditional operators "?." [duplicate]如何重载空条件运算符“?” [复制]
【发布时间】: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#


【解决方案1】:

不,您不能重载Null-conditional operators。请参阅 C#Overloadable operators 列表。


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

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

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

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

【讨论】:

    猜你喜欢
    • 2012-03-14
    • 1970-01-01
    • 2017-01-29
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    相关资源
    最近更新 更多