C#反序列化-捕获targeting异常是否安全?

C#反序列化-捕获targeting异常是否安全?,c#,deserialization,targetinvocationexception,C#,Deserialization,Targetinvocationexception,我正在使用BinaryFormatter序列化和反序列化一些对象。这些对象的结构如下: [Serializable()] public class SerializableObject : ISerializable { public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("SomeProperty", SomeProperty);

我正在使用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;
    }
}

我们都知道,捕获您不知道如何处理或无法处理的异常是一种糟糕的做法,所以我想问,在这里捕获异常是否安全?是否可以出于任何其他原因(我不知道,因此不应该处理)引发相同的异常?

A
TargetInvokationException
应该有一个
InnerException
,它将为您提供更多信息。我建议您检查catch块中的内部,如果情况只是缺少属性,则重新调用。

因为
TargetInvocationException
没有列在您应该从该方法()获得的异常集中,我认为尝试处理该异常是错误的。一种更好的方法是循环使用它确实拥有的名称,并选择您期望的名称:

    foreach(SerializationEntry entry in info)
    {
        switch(entry.Name)
        {
            case "Foo": //...   
            case "Bar": //...
        }
    }
或者。。。使用不太挑剔的序列化程序;p


(顺便说一句,上面使用了基于类型化枚举器和
GetEnumerator()
方法的可选
foreach
处理;它没有实现
IEnumerable
/
IEnumerable
,但是……它不必实现;您可以使用
foreach
,而不必实现)

DataContractSerializer还是别的什么?@Ritch我可以接受
DataContractSerializer
——它至少是基于契约的,这是向前迈出的一大步。虽然我几乎总是接触protobuf-net,但我在这方面有点偏颇。@Marc-protobuf-net还在测试版吗?您现在会提倡在生产代码中使用它吗假装没有偏见;)@David oh,v1已经“脱离测试版”多年了;v2当然是生产安全的(我们每天在这里使用数百万次)-然而,有一些很少使用的、小众的方法,大多数人不会错过,但还没有完全重新创建-这就是它等待的全部。