![](/img/trans.png)
[英]Why isn't my cast operator from T to SomeStruct<T> working when T is an interface?
[英]Why isn't it possible to define implicit cast operator from interface to class?
说,我有一个界面
public interface ISomeControl
{
Control MyControl { get; }
...
}
是否可以定义这样的东西:
public static implicit operator Control(ISomeControl ctrl)
{
return ctrl.MyControl;
}
或者更确切地说,为什么我不能在C#中这样做?
如果你有一个Control
的子类,那个子类实现了ISomeControl
接口ISomeControl
?
class SomeControl : Control, ISomeControl {}
现在演员阵容不明确 - 内置向上播放和用户定义的转换。 因此,您无法为接口提供用户定义的转换。
你不能这样做。
C#规范说:
6.4.1允许的用户定义转换
C#仅允许声明某些用户定义的转换。 特别是,无法重新定义已存在的隐式或显式转换。 对于给定的源类型S和目标类型T,如果S或T是可空类型,则让S0和T0引用它们的基础类型,否则S0和T0分别等于S和T. 仅当满足以下所有条件时,才允许类或结构声明从源类型S到目标类型T的转换:
S0和T0是不同的类型。
S0或T0是发生运算符声明的类或结构类型。
S0和T0都不是接口类型。
排除用户定义的转换,从S到T或从T到S不存在转换。
一种方法是使用静态方法。
public class Control
{
public static Control FromISomeControl(ISomeControl ctrl)
{
return ctrl.MyControl;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.