gpt4 book ai didi

c# - 编译器如何为实数文字选择隐式运算符重载

转载 作者:行者123 更新时间:2023-12-03 15:12:47 27 4
gpt4 key购买 nike

鉴于以下代码 - 哪个 C# 规则导致实数文字被强制转换为 int 并且首选第一个隐式运算符重载而不是第二个?

class Dong
{
public static implicit operator Dong(int i) { return null; }

public static implicit operator Dong(decimal d) { return null; }

static void Main()
{
var d = (Dong)123.1;
}
}

最佳答案

阅读 this ,特别是这部分:

Processing of user-defined explicit conversions

A user-defined explicit conversion from type S to type T is processed as follows:

  • Determine the types S0 and T0. If S or T are nullable types, S0 andT0 are their underlying types, otherwise S0 and T0 are equal to S andT respectively.

  • Find the set of types, D, from which user-defined conversionoperators will be considered. This set consists of S0 (if S0 is aclass or struct), the base classes of S0 (if S0 is a class), T0 (ifT0 is a class or struct), and the base classes of T0 (if T0 is aclass).

  • Find the set of applicable user-defined and lifted conversionoperators, U. This set consists of the user-defined and liftedimplicit or explicit conversion operators declared by the classes orstructs in D that convert from a type encompassing or encompassed byS to a type encompassing or encompassed by T. If U is empty, theconversion is undefined and a compile-time error occurs.

  • Find the most specific source type, SX, of the operators in U:

    If any of the operators in U convert from S, then SX is S.

    Otherwise, if any of the operators in U convert from types that encompass S, then SX is the most encompassed type in the combined set of source types of those operators. If no most encompassed type can be found, then the conversion is ambiguous and a compile-time error occurs.

    Otherwise ...


加粗部分适用;这里最广泛的类型是 int因为它可以隐式转换为 doubledecimal不能隐式转换为 double :

The most encompassed type in a set of types is the one type that is encompassed by all other types in the set. If no single type is encompassed by all other types, then the set has no most encompassed type. In more intuitive terms, the most encompassed type is the "smallest" type in the set—the one type that can be implicitly converted to each of the other types.

关于c# - 编译器如何为实数文字选择隐式运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60112801/

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