【问题标题】:protobuf-net - list supported typesprotobuf-net - 列出支持的类型
【发布时间】:2019-01-14 07:17:01
【问题描述】:

我正在开发一个自定义 ProtoBufFormatter (: MediaTypeFormatter),它能够将自己的类型动态注册到用于序列化/反序列化的 RuntimeTypeModel。

为了减少对 try{}catch{} 块的需求,最好在将已支持的类型添加到 RuntimeTypeModel 之前过滤掉它们。自述文件仅提供默认支持的“模糊”列表类型,并且 Model.GetTypes() 方法仅返回手动添加到当前模型的类型列表。

自述文件:https://github.com/mgravell/protobuf-net

我正在使用 protobuf-net 2.4.0

所以我想知道是否有任何简单的方法来检查当前 RuntimeTypeModel 是否已经支持一个类型? 目前我正在使用这样的东西来预过滤类型:

    private bool IsSimpleType(Type type)
    {
        return
            type.IsPrimitive ||
            _additionalSimpleTypes.Contains(type) ||
            Convert.GetTypeCode(type) != TypeCode.Object ||
            (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>) && IsSimpleType(type.GetGenericArguments()[0]));
    }

    private Type[] _additionalSimpleTypes = new Type[]
    {
                typeof(Enum),
                typeof(String),
                typeof(String[]),
                typeof(Decimal),
                typeof(DateTime),
                typeof(DateTimeOffset),
                typeof(TimeSpan),
                typeof(Guid),
                typeof(Uri),
                typeof(Byte),
                typeof(Byte[]),
                typeof(Char),
                typeof(Boolean),
                typeof(Object),
                typeof(Version)
    };

    private Type[] _listTypes = new Type[]
    {
        typeof(Enum),
                typeof(IEnumerable<>),
                typeof(List<>),
                typeof(IList<>)
    };

【问题讨论】:

  • 我认为今天不存在这样的方法;我们当然可以加一个……
  • 那太好了。任何其他想法如何在没有 try'n'error 的情况下测试类型是否已被支持?

标签: c# protobuf-net


【解决方案1】:

试试:

 ProtoBuf.Meta.RuntimeTypeModel.Default.CanSerialize(Type type)

【讨论】:

    猜你喜欢
    • 2011-06-13
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多