簡體   English   中英

C#反序列化-可以安全地捕獲TargetInvocationException嗎?

[英]C# Deserialization - Is it safe to catch TargetInvocationException?

我正在使用BinaryFormatter序列化和反序列化某些對象。 這些對象的結構如下:

[Serializable()]
public class SerializableObject : ISerializable
{
    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("SomeProperty", SomeProperty);
        // similar for other properties
    }

    public SerializableObject(SerializationInfo info, StreamingContext context)
    {
        this.SomeProperty = (SomePropertyClass)info.GetValue("SomeProperty", typeof(SomePropertyClass));
        // similar for other properties
    }
}

我注意到,當我嘗試反序列化對象時,如果找不到“ SomeProperty”條目(例如,因為它被重命名或刪除),則會引發TargetInvocation異常。 由於我打算將來更改SerializableObject類的屬性,因此我在考慮捕獲異常並將有問題的屬性的值設置為某個默認值,而不是使應用程序崩潰,例如:

public SerializableObject(SerializationInfo info, StreamingContext context)
{
    try
    {
        this.SomeProperty = (SomePropertyClass)info.GetValue("SomeProperty", typeof(SomePropertyClass));
    }
    catch (TargetInvocationException)
    {
        this.SomeProperty = SomePropertyClass.DefaultValue;
    }
}

眾所周知,捕獲您不知道如何處理或無法處理的異常是一種不好的做法,所以我問在這個地方捕獲它是否安全? 可以出於任何其他原因(我不知道,因此不應處理)拋出相同的異常嗎?

TargetInvokationException應該具有一個InnerException ,它將為您提供更多信息。 我建議您檢查catch塊的內部,如果情況僅僅是缺少的屬性,則重新拋出。

由於TargetInvocationException 沒有列在您應該從該方法獲得的異常集中( 請參見MSDN ),我會說嘗試處理該錯誤是錯誤的。 更好的方法是循環使用它確實具有的名稱,然后選擇所需的名稱:

    foreach(SerializationEntry entry in info)
    {
        switch(entry.Name)
        {
            case "Foo": //...   
            case "Bar": //...
        }
    }

或者...使用不太繁瑣的序列化器; p

(順便說一句,以上方法基於類型化的枚舉器和GetEnumerator()方法使用了替代的foreach處理;它沒有實現IEnumerable / IEnumerable<T> ,但是...並不一定要實現;您可以在沒有該方法的情況下使用foreach

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM