問(wèn)題描述
參考使自定義.NET Exception 可序列化的正確方法是什么?
和 所有 .NET 異常都可序列化嗎? ...
為什么我的異常應(yīng)該是可序列化的?
有人說(shuō),如果第三方庫(kù)定義的自定義異常是不可序列化的,它可以被認(rèn)為是一個(gè)錯(cuò)誤".為什么?
Why should my exceptions be serializable?
Someone said "it can be considered a bug" if a custom exception defined by a third party library, is not serializable. Why?
為什么在這方面異常與其他類不同?
Why are exceptions different than other classes in this regard?
推薦答案
因?yàn)槟漠惓?赡苄枰诓煌?AppDomain 之間進(jìn)行編組,如果它們不能(正確)序列化,您將丟失寶貴的調(diào)試信息.與其他類不同,您無(wú)法控制您的異常是否會(huì)被編組——它會(huì).
Because your exceptions may need to be marshalled between different AppDomains and if they aren't (properly) serializable you will lose precious debugging information. Unlike other classes, you won't have control over whether your exception will be marshalled -- it will.
當(dāng)我的意思是你將無(wú)法控制"時(shí),我的意思是你創(chuàng)建的類通常具有有限的存在空間,并且存在是眾所周知的.如果它是一個(gè)返回值并且有人試圖在不同的 AppDomain(或在不同的機(jī)器上)調(diào)用它,他們會(huì)得到一個(gè)錯(cuò)誤,并且可以說(shuō)不要那樣使用它".調(diào)用者知道他們必須將其轉(zhuǎn)換為可以序列化的類型(通過(guò)包裝方法調(diào)用).但是,由于如果沒(méi)有被捕獲,異常就會(huì)冒泡到最頂端,它們可以超越您甚至不知道的 AppDomain 邊界.您在不同 AppDomain 中的 20 級(jí)自定義應(yīng)用程序異??赡苁?Main() 報(bào)告的異常,并且在此過(guò)程中沒(méi)有任何東西可以將其轉(zhuǎn)換為您的可序列化異常.
When I mean "you won't have control" I mean that classes you create generally have a finite space of existence and the existence is well known. If it's a return value and someone tries to call it in a different AppDomain (or on a different machine) they will get a fault and can just say "Don't use it that way." The caller knows they have to convert it into a type that can be serialized (by wrapping the method call). However since exceptions are bubbled up to the very top if not caught they can transcend AppDomain boundaries you didn't even know you had. Your custom application exception 20 levels deep in a different AppDomain might be the exception reported at Main() and nothing along the way is going to convert it into a serializable exception for you.
這篇關(guān)于為什么我應(yīng)該總是讓我的異常[可序列化]?(.網(wǎng))的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!