小编mic*_*hut的帖子

如何显式地从Nullable <T>转换

我已经定义了自定义值类型MyCustomValueType,隐式转换运算符从long到MyCustomValueType.

public struct MyCustomValueType
{
    private readonly long number;

    public MyCustomValueType(long? number)
    {
        this.number = number.GetValueOrDefault(0);
    }

    public static implicit operator MyCustomValueType(long number)
    {
        return new MyCustomValueType(number);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后编译器允许我执行以下操作:

// ...
long? value = null;
MyCustomValueType myCustomValueType = (MyCustomValueType)value;
Console.WriteLine(myCustomValueType);
Run Code Online (Sandbox Code Playgroud)

在引擎盖下,编译器将使用强制转换的语句转换为:

MyCustomValueType myCustomValueType = ((long?)null).Value;
Run Code Online (Sandbox Code Playgroud)

我想知道(或更好地说WHY)是怎么发生的?为什么编译器甚至允许显式转换没有定义任何人.编译器适用的规则是什么?


我可能还应该提到,当MyCustomValueType仅定义用于强制转换的显式运算符时,也可以进行此类强制转换,例如:

public static explicit operator MyCustomValueType(long number)
Run Code Online (Sandbox Code Playgroud)

但在这种情况下,我以某种方式接受编译器的作用并理解它.隐式运算符的情况确实令人困惑.有人可以解释一下吗?

c# casting nullable implicit-cast

2
推荐指数
1
解决办法
213
查看次数

标签 统计

c# ×1

casting ×1

implicit-cast ×1

nullable ×1