如何建立遠端物件可擲回的例外狀況類型
從 RemotingException 衍生物件並實作 ISerializable 介面,即可建立遠端物件可擲回、遠端呼叫端可攔截的自訂例外狀況類型。
建立遠端物件可擲回且遠端呼叫端可攔截的例外狀況類型
定義從 RemotingException 類別衍生的類別。
Public Class RemotableType Inherits MarshalByRefObject End Class 'RemotableType
public class RemotableType : MarshalByRefObject{ }
將 SerializableAttribute 屬性放在類別上。
<Serializable()> Public Class CustomRemotableException Inherits RemotingException End Class
[Serializable] public class CustomRemotableException : RemotingException, ISerializable { }
實作使用 SerializationInfo 物件和 StreamingContext 物件做為參數的還原序列化建構函式。
範例
下列程式碼範例提供當被遠端伺服器物件擲回時,會複製回呼叫端的簡單實作 (如果已設定)。
<Serializable()> Public Class CustomRemotableException
Inherits RemotingException
Private _internalMessage As String
Public Sub CustomRemotableException()
_internalMessage = String.Empty
End Sub
Public Sub CustomRemotableException(ByVal message As String)
_internalMessage = message
End Sub
Public Sub CustomRemotableException(ByVal info As _
SerializationInfo, ByVal context As StreamingContext)
_internalMessage = info.GetValue("_internalMessage", _
_internalMessage.GetType())
End Sub
Public Overrides Sub GetObjectData(ByVal info As SerializationInfo, _
ByVal context As StreamingContext)
info.AddValue("_internalMessage", _internalMessage)
End Sub
Public Shadows ReadOnly Property Message() As String
Get
Return "This is your custom remotable exception returning: \"" " +
_internalMessage + "\"";"
End Get
End Property
End Class
[Serializable]
public class CustomRemotableException : RemotingException, ISerializable {
private string _internalMessage;
public CustomRemotableException(){
_internalMessage = String.Empty;
}
public CustomRemotableException(string message){
_internalMessage = message;
}
public CustomRemotableException(SerializationInfo info, StreamingContext context){
_internalMessage = (string)info.GetValue("_internalMessage", typeof(string));
}
public override void GetObjectData(SerializationInfo info, StreamingContext context){
info.AddValue("_internalMessage", _internalMessage);
}
// Returns the exception information.
public override string Message{
get {
return "This is your custom remotable exception returning: \""
+ _internalMessage
+ "\"";
}
}
}