If an identity conversion exists from S to T, must it be that S and T are same type?

陌路散爱 提交于 2021-02-07 05:21:12

问题


In 6.1.6. of the C# language specification, there is:

The implicit reference conversions are:

(...)
From any reference-type to a reference-type T if it has an implicit identity or reference conversion to a reference-type T0 and T0 has an identity conversion to T.

Why don't they say instead, more simply:

From any reference-type to a reference-type T if it has an implicit identity or reference conversion to T.

Is there any factual difference?

EDIT: I realized I mistyped the specification and the error could potentially be significant for the question (the specification says "The implicit reference conversion are" rather than "An implicit conversion exists")


回答1:


If an identity conversion exists from S to T, must it be that S and T are same type?

The oddity you've discovered in the spec arose as a result of adding dynamic to the language in C# 4.0. At runtime there is no such thing as dynamic; rather, dynamic is just a type that means "I'm really object; please defer analysis of this portion of the program until runtime".

Therefore there is an identity conversion between, say, List<object> and List<dynamic>. From the C# compiler's perspective they are different types because myList[0].Frob() would give an error for the former but not the latter. But from the runtime's perspective they are identical. Therefore the C# language classifies the conversion from one to the other as an identity conversion. At compile time the types can be different for the purposes of the C# language, but from the runtime's perspective they will be identical.



来源:https://stackoverflow.com/questions/20935319/if-an-identity-conversion-exists-from-s-to-t-must-it-be-that-s-and-t-are-same-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!