protobuf-net - 列出支持的类型

M. *_*ann 4 c# protobuf-net

我正在开发一个自定义 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<>)
    };
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 5

尝试:

 ProtoBuf.Meta.RuntimeTypeModel.Default.CanSerialize(Type type)
Run Code Online (Sandbox Code Playgroud)