c# - 可以重载空合并运算符吗?

标签 c# .net operator-overloading null-coalescing-operator

是否可以为 C# 中的类重载 null 合并运算符?

例如,如果实例为 null,我想返回一个默认值,如果不是,则返回该实例。代码看起来像这样:

   return instance ?? new MyClass("Default");  

但是,如果我想使用 null 合并运算符来检查是否设置了 MyClass.MyValue 怎么办?

最佳答案

好问题!它没有在 list of overloadable and non-overloadable operators 中以一种或另一种方式列出the operator's page 上没有提到任何内容.

所以我尝试了以下方法:

public class TestClass
{
    public static TestClass operator ??(TestClass  test1, TestClass test2)
    {
        return test1;
    }
}

我收到错误“预期可重载二元运算符”。所以我想说,从 .NET 3.5 开始,答案是否定的。

关于c# - 可以重载空合并运算符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/349062/

相关文章:

C++分配给指针一个指向常量的指针

c++ - 在 C++ 中重载运算符 `:=`

c# - 为什么Notepad++ [NULL] 字符不粘贴?

c# - 安装时启动 Windows 服务,无需安装项目

c# - 以编程方式确定当前域 Controller

c# - 你会分享你的想法如何从嵌入式 Python.Net 调用 python 命令吗?

c# - WPF 调用控件

c# - 如何防止类 'a' 被另一个类继承?

c# - Winforms .NET 4.5 应用程序在新机器上崩溃

c++ - 重写 operator>> 用于 Strings 类