int
不是bool
。試試看看會發生什麼(InvalidCastException)。
![InvalidlCastException thrown](https://i.stack.imgur.com/pVMPM.png)
應該注意的是最原始類型的明確實現IConvertible
,這樣你就可以得到投你要這樣說:
int a = 37 ;
object b = a ;
bool c = (b as IConvertible) != null && (b as IConvertible).ToBoolean(null);
在int
→ bool
轉換等的情況下這個轉換是以通常的類C方式完成的:零爲false
,非零爲true
。值得注意的是,這種行爲與形式邏輯不一致,在形式邏輯中,僞造是多值的,所有這些都不是真實的,而且是單值的。但我離題了。
就自定義轉換而言,無論是隱式還是顯式,您所做的只是提供由編譯器識別爲運算符的自定義方法。 如何的轉換,當然取決於你和你的實現。在這裏,類Foo
知道如何給自己[明確]轉換爲Bar
類的一個實例:
class Foo
{
public static explicit operator Bar(Foo x)
{
// your implementation here
throw new NotImplementedException();
}
}
這裏,類Bar
知道如何[明確]本身轉換爲int
和[隱式]轉換本身到Foo
:
class Bar
{
public static explicit operator int(Bar x)
{
// your implementation here
throw new NotImplementedException();
}
public static implicit operator Foo(Bar x)
{
// your implementation here
throw new NotImplementedException();
}
}
當您啓動混合東西了,編譯器會找出轉換方法(S)都適用(或不)並加以解決。您將得到關於轉換的編譯錯誤,或者編譯將選擇一個轉換方法在運行時調用。
在運行時,當然可能會在轉換過程中拋出異常。
另請參閱:http://blogs.msdn.com/b/ericlippert/archive/2009/03/19/representation-and-identity.aspx – 2014-10-28 19:25:51