gpt4 book ai didi

c# - "From any class-type S to any interface-type T, provided S is not sealed and provided S does not implement T."到底是什么意思?

转载 作者:太空狗 更新时间:2023-10-29 20:29:09 27 4
gpt4 key购买 nike

什么是“从任何类类型 S 到任何接口(interface)类型 T,前提是 S 不是密封的并且前提是 S 不实现 T。”究竟是什么意思?

我在 C# 语言规范中遇到了这个 here :

6.2.4 Explicit reference conversions

The explicit reference conversions are:

  • ...
  • From any class-type S to any interface-type T, provided S is not sealed and provided S does not implement T.

我能理解“提供 S 未密封”的含义,但我不确定我是否理解“提供 S 未实现 T”的真正含义。

例如:

class S {}//not sealed, nor does it implement T
interface T {}
...
T t = (T)new S();//will throw InvalidCastException.

难道规范中只是列举了所有语法上正确的表达显式引用转换的方式,而不管它是否会抛出异常?或者它是否意味着我不知道的其他事情(截至目前)?

提前致谢。

最佳答案

双关语在“未密封”部分:

class S {} //not sealed, nor does it implement T
interface T {}

class S2 : S, T { }

S s = new S2(); // S reference to an S2 instance, implicit conversion
T t = (T)s; // OK, s refers to an S2 instance that does implement T

Could it be that it is in the specs only to enumerate all syntactically correct ways of expressing an explicit reference conversion, ...

是的,编译器必须允许它,除非它知道转换是不可能的。

如果您查看 T t = (T)s;,如果 S 是密封的,那么编译器可以肯定地知道转换是不可能的。但是对于未密封的 S,它必须消除 s 引用 S2 类型的可能性,这是不实际/不可能的( S2 可能在另一个程序集中)。

关于c# - "From any class-type S to any interface-type T, provided S is not sealed and provided S does not implement T."到底是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3715476/

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