Why does SerializationInfo not have TryGetValue methods?

非 Y 不嫁゛ 提交于 2019-12-21 07:02:59

问题


When implementing the ISerializable interface in C#, we provide a constructor which takes a SerializationInfo object, and then queries it with various GetInt32, GetObject etc. methods in order to fill the fields of the object which we are trying to deserialize.

One major reason to implement this interface, rather than just using the [Serializable] attribute, is for backwards compatibility: if we have added new fields to the class at some point, we can catch the SerializationException thrown by a serialized, older version of the class, and handle them in an appropriate manner.

My question is the following: why do we have to use these exceptions for what is, essentially, control flow? If I am deserializing a large number of classes which were saved some time ago, potentially each missing field in each class will throw an exception, causing really bad performance.

Why does the SerializationInfo class not provide TryGetValue methods which would simply return false if the name string were not present?


回答1:


You can iterate over the available fields and use switch, though...

            foreach(SerializationEntry entry in info) {
                switch(entry.Name) {
                    ...
                }
            }

Or you could use protobuf-net ;-p




回答2:


Well no one answered 'why', but I'm guessing that's addressed to MS..

My implementation for anyone in need:

public static class SerializationInfoExtensions
{
    public static bool TryGetValue<T>(this SerializationInfo serializationInfo, string name, out T value)
    {
        try
        {
            value = (T) serializationInfo.GetValue(name, typeof(T));
            return true;
        }
        catch (SerializationException)
        {
            value = default(T);
            return false;
        }
    }

    public static T GetValueOrDefault<T>(this SerializationInfo serializationInfo, string name, Lazy<T> defaultValue)
    {
        try
        {
            return (T) serializationInfo.GetValue(name, typeof(T));
        }
        catch (SerializationException)
        {
            return defaultValue.Value;
        }
    }
}


来源:https://stackoverflow.com/questions/1673208/why-does-serializationinfo-not-have-trygetvalue-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!