繁体   English   中英

可序列化的反序列化性能

[英]ISerializable de-serialization performance

在实现ISerializable时,您编写诸如此类的代码以执行自定义反序列化...

(注意:这是一个简单的示例,不保证自定义反序列化)。

protected ClientInformation(SerializationInfo info, StreamingContext context)
{
    _culture = (string)info.GetValue("Culture", typeof(string))
}

对于GetValue方法,需要您希望反序列化的类型,根据智能感知帮助,它可以执行以下操作

“如果存储的值不能转换为此类型,则系统将引发System.InvalidCast异常”

这是否意味着在我的示例语句中正在执行两个强制转换?

此外,添加此类型参数的意义是什么,因为如果我编写以下代码,

_culture = info.GetValue("Culture", typeof(string))

...这将不会编译,因为您“无法将类型'object'隐式转换为'string'”。 因此,这意味着无论如何我都必须转换对象,因此,如果转换无效,无论如何我都会通过自己的转换得到InvalidCastException。

似乎在这里发生了两次强制转换,并且在任何情况下同样仅在运行时才会发生错误(无法通过泛型实现编译类型检查),除非有人知道发生这种情况的原因?

更新:可能是在后台使用“是”运算符检查类型是预期的吗? 是否“是”会自动尝试投射?

如果我们看一下GetValue的实现,似乎对象本身没有被强制转换,但是至少发生了一次强制转换(从Type到RuntimeType)。

据我所知,还有一些检查认为您的对象是否被投射不那么重要。

public object GetValue(string name, Type type)
{
    Type type3;
    if (type == null)
    {
        throw new ArgumentNullException("type");
    }
    RuntimeType castType = type as RuntimeType;
    if (castType == null)
    {
        throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
    }
    object element = this.GetElement(name, out type3);
    if (RemotingServices.IsTransparentProxy(element))
    {
        if (RemotingServices.ProxyCheckCast(RemotingServices.GetRealProxy(element), castType))
        {
            return element;
        }
    }
    else if ((object.ReferenceEquals(type3, type) || type.IsAssignableFrom(type3)) || (element == null))
    {
        return element;
    }
    return this.m_converter.Convert(element, type);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM