可以覆盖空合并运算符? [英] Possible to override null-coalescing operator?
问题描述
是否有可能重写空合并运算符一类在C#中?
Is it possible to override the null-coalescing operator for a class in C#?
说,例如,我想回到一个默认值,如果一个实例为null,并返回举例来说,如果它不是。在code看起来就像是这样的:
Say for example I want to return a default value if an instance is null and return the instance if it's not. The code would look like something like this:
return instance ?? new MyClass("Default");
但是,如果我想使用空合并运算符还检查MyClass.MyValue设置?
But what if I would like to use the null-coalescing operator to also check if the MyClass.MyValue is set?
当然有这个没有真正的需要(至少我认为是这样) - 让你回答之前,为什么你会想这样做。 - 我是否有可能只是好奇
Of course there is no real need for this (at least I think so) - so before you answer "why would you want to do that" - I am just curious if it's possible.
推荐答案
问得好!它没有列出一个或在重载与非重载运营商和什么也没有提到列表拉上在运营商的页面。
Good question! It's not listed one way or another in the list of overloadable and non-overloadable operators and nothing's mentioned on the operator's page.
于是,我尝试了以下内容:
So I tried the following:
public class TestClass
{
public static TestClass operator ??(TestClass test1, TestClass test2)
{
return test1;
}
}
和我得到的错误重载的二元运算符预期。所以,我想说的答案是,作为.NET 3.5,一个没有。
and I get the error "Overloadable binary operator expected". So I'd say the answer is, as of .NET 3.5, a no.
这篇关于可以覆盖空合并运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!