我可以在 C# 中重载“从空值转换”运算符吗?

gex*_*ide 5 c# null struct

我在 C# 中有一个结构类型。我希望能够null隐式转换为这种类型。例如,null可以由结构类型的特殊值表示,并且强制转换运算符应返回具有此值的结构。

在 C++ 中,我可以使用 type 的隐式强制转换运算符重载std::nullptr_t。C# 中有类似的类型吗?

我有使用一个NullType没有实例的特殊类的想法。这有效,但看起来有点难看。有没有更好的办法?

例子:

class NullType
{
    private NullType(){} // ensures that no instance will ever be created
}

struct X
{
    private static readonly int nullValue = -1;
    private int val;

    public X(int val){ this.val= val; }

    public static implicit operator X(NullType t)
    { 
        return new X(nullValue);
    }
}

class MainClass
{
     public static void Main(string[] args)
     {
          X x = null; // Works now!
     }
}
Run Code Online (Sandbox Code Playgroud)

Pat*_*man 1

不,转换运算符只允许从类型进行转换,而不允许从类型的特定值(又名 )进行转换null,因此没有null转换运算符。

不引入自己的类型的最合适的运算符是这样的:

public static implicit operator X(object t)
Run Code Online (Sandbox Code Playgroud)

但显然你不想使用这个。使用起来不太安全(t可以是任何值,并且是处理异常中非空情况的唯一方法)。

也就是说,我认为您现在创建它的方式,使用无法初始化的类是执行此操作的最佳方法。事实上,唯一的问题是:为什么要使用null,而不是“仅”结构上的默认值实例 ( X.Null)。