是否可以为 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/