有关C#语言规范中的隐式转换的问题 [英] Question regarding implicit conversions in the C# language specification

查看:82
本文介绍了有关C#语言规范中的隐式转换的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第6.1节隐式转换由此定义了身份转换:

身份转换从任何类型转换为相同类型.这种转换的存在使得可以将已经具有必需类型的实体转换为该类型.

An identity conversion converts from any type to the same type. This conversion exists such that an entity that already has a required type can be said to be convertible to that type.

现在,诸如此类的句子的目的是什么?

Now, what is the purpose of sentences such as these?

(在第6.1.6节中,隐式引用转换)

隐式引用转换为:

  • [...]
  • 从任何引用类型引用类型 T,如果它具有隐式标识或对引用类型 T 0 T 0 的身份转换为T.
  • [...]
  • 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.

和:

(在§6.1.7装箱转换中)

  • 如果值类型可以将接口类型I 0 I 0 进行拳击转换,则可以将其转换为接口类型I已将身份转换为I.
  • A value type has a boxing conversion to an interface type I if it has a boxing conversion to an interface type I0 and I0 has an identity conversion to I.

最初,它们似乎是多余的(互斥的).但是它们必须出于目的而存在,为什么要在那里?

Initially they seem redundant (tautologous). But they must be there for a purpose, so why are they there?

您能举两个类型T 1 T 2 的示例,这样T 1 如果不是上述段落, not 是否可以隐式转换为T 2 ?

Can you give an example of two types T1, T2 such that T1 would not be implicitly convertible to T2 if it weren’t for the above-quoted paragraphs?

推荐答案

规范的4.7节指出,存在从Foo<dynamic>Foo<object>的身份转换,反之亦然.编写您引用的规范部分以确保能够处理这种情况.也就是说,如果存在从T到C<object, object>的隐式引用转换,那么也存在到C<object, dynamic>C<dynamic, object>C<dynamic, dynamic>的隐式引用转换.

Section 4.7 of the specification notes that there is an identity conversion from Foo<dynamic> to Foo<object> and vice versa. The portion of the spec you quoted is written to ensure that this case is handled. That is, if there is an implicit reference conversion from T to C<object, object> then there is also an implicit reference conversion to C<object, dynamic>, C<dynamic, object> and C<dynamic, dynamic>.

一个人可能会合理地指出(1)这些短语的意图不明显-因此您的问题-令人困惑,并且(2)身份转换部分应交叉引用动态转换部分,并且( 3)规范中的此类短语使规范的实现者很难将规范语言明确转换为实现.如何知道这种类型是否存在?该规范不需要指定确切的算法,但是如果能提供更多指导,那就更好了.

One might reasonably point out that (1) the intention of these phrases is unobvious - hence your question - and confusing, and (2) that the section on identity conversions ought to cross-reference the section on dynamic conversions, and (3) phrases like this in the spec make it difficult for an implementor of the specification to clearly translate the spec language into an implementation. How is one to know if any such type exists? The spec need not specify exact algorithms, but it would be nice if it gave more guidance.

可悲的是,该规范不是完美的文档.

The spec is, sadly, not a perfect document.

这篇关于有关C#语言规范中的隐式转换的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆