gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:43:29 25 4
gpt4 key购买 nike

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

在 C++ 中,我可以使用 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!
}
}

最佳答案

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

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

public static implicit operator X(object t)

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

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

关于c# - 我可以在 C# 中重载 "cast from null"运算符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31454919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com