operator,绕道implicit operator隐转接口

c#的implicit operator是一个定义隐式类型转换的接口,不过c#不允许interface参与其中,也即,以下代码是被拒绝的:
class A { public static implicit operator A(IEnumerable e) { return null; } }
编译器道: user-defined conversions to or from an interface are not allowed
老爷以为interface的隐转是有必要的,叵耐c#编译器必要来相阻,正没作理会处,看见园友 装配脑袋 的一篇博文的回复中有提到SpecialName attribute,且去一试
果然绕过了c#:
public class A { [SpecialName] public static A op_Implicit(IEnumerable e) { return null; } }
然后即可:
A a="abc";
只是波浪线看着心乱-_-!
Tags:  implicit operator

延伸阅读

最新评论

发表评论