gpt4 book ai didi

c# - 当存在从 int 到 Foo 的显式用户定义运算符时,为什么编译器会隐式地将 double 转换为 int?

转载 作者:太空狗 更新时间:2023-10-29 22:30:21 24 4
gpt4 key购买 nike

为什么显式转换自doubleFoo可能,即使Foo仅定义了从 int 的显式转换至 Foo

为什么在我的案例中是double隐式转换为 int

using System;

class Program
{
static void Main(string[] args)
{
double doub = 15.7;
Foo foo = (Foo)doub;
Console.WriteLine(foo.value); //writes "15"
}
}

struct Foo
{
public int value;
public static explicit operator Foo(int val) //no matter if implicit
{
return new Foo { value = val };
}
}

最佳答案

我相信这在 C# 5 语言规范的第 6.4.3 节中有规定。

第 6.2.8 节用户定义的显式转换(强调我的)给出了第一个提示:

A user-defined explicit conversion consists of an optional standard explicit conversion, followed by execution of a user-defined implicit or explicit conversion operator, followed by another optional standard explicit conversion

请注意如何发生不是一次而是可能的 3 次转化。

现在,要了解什么是“标准显式转换”,我们必须查看 6.2.3 标准显式转换部分:

The standard explicit conversions are all standard implicit conversions plus the subset of the explicit conversions for which an opposite standard implicit conversion exists. In other words, if a standard implicit conversion exists from a type A to a type B, then a standard explicit conversion exists from type A to type B and from type B to type A.

回顾6.3.1 Standard implicit conversions部分,我们可以看到这是其中的一部分:

  • Implicit numeric conversions (§6.1.2)

换句话说:可以在用户定义的转换之前应用显式数字转换(如 double -> int)。

如果我们现在查看 6.4.3 Evaluation of user-defined conversions,我们会看到以下内容(强调我的):

First, if required, performing a standard conversion from the source type to the operand type of the userdefined or lifted conversion operator

Next, invoking the user-defined or lifted conversion operator to perform the conversion.

Finally, if required, performing a standard conversion from the result type of the user-defined or lifted conversion operator to the target type.

这正是您的场景中发生的情况。

关于c# - 当存在从 int 到 Foo 的显式用户定义运算符时,为什么编译器会隐式地将 double 转换为 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35689483/

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