【问题标题】:ISerializable de-serialization performanceISerializable 反序列化性能
【发布时间】:2011-11-29 15:06:12
【问题描述】:

在实现 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。

这里会出现两次强制转换,同样在任何情况下,错误都只能在运行时发生(不能通过泛型实现编译类型检查),除非有人知道发生这种情况的原因?

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

【问题讨论】:

  • 强制转换高度在处理序列化时不太可能成为瓶颈 - 序列化通常适用于某些慢速介质(例如内存、网络或磁盘)已经存在的情况参与。
  • 是的,只是想知道演员阵容是否超出了要求。

标签: c# .net serialization iserializable


【解决方案1】:

如果我们查看 GetValue 的实现,似乎对象本身没有被转换,但至少发生了一次转换(Type to 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);
}

【讨论】:

    猜你喜欢
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多