2010-06-10 120 views

回答

9

您需要在MyClass文件来定义这一点。

public static implicit operator int(MyClass instance) 
{ 
    if (instance == null) 
    { 
     return -1; 
    } 
    return instance._underlyingValue; 
} 
+0

它应该是一个int?隐式转换,所以不需要是魔法值?特别是如果-1可能是合法的基础价值。我认为对于这种情况,如果转换不可能或抛出异常,您要么返回null。 (显然你的答案符合规范,所以这更多的是对规范的质疑而不是回答。) – 2010-06-10 17:14:49

+1

@Anthony - 原则上,我同意你的看法。在实践中,它高度依赖于所讨论的课程。 – ChaosPandion 2010-06-10 17:18:51

4
class MyClass 
{ 
    public static implicit operator int(MyClass myClass) 
    { 
     // code to convert from MyClass to int 
    } 
} 

看看有:implicit

2

MSDN entry涵盖了你想要什么,应该做的伎俩。

相关问题