我可以在 C# 中重载 "cast from null" 运算符吗?

Can I overload a "cast from null" operator in C#?

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

在 C++ 中,我可以使用 std::nullptr_t 类型的隐式转换运算符重载。 C# 中是否有可比较的类型?

我想使用一个没有实例的特殊 NullType class。这有效但看起来有点丑陋。有没有更好的方法?

示例:

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!
     }
}

不,转换运算符只允许从类型转换,而不是从类型的特定值转换,也就是 null,因此没有 null 转换运算符。

不引入自己的类型的最佳拟合运算符是:

public static implicit operator X(object t)

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

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