- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
鉴于以下代码 - 哪个 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
因为它可以隐式转换为
double
而
decimal
不能隐式转换为
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/
我是一名优秀的程序员,十分优秀!