protobuf-net - list supported types

拥有回忆 提交于 2019-12-10 18:23:09

问题


I'm working on a custom ProtoBufFormatter (: MediaTypeFormatter) that is capable of registering own types on the fly to the RuntimeTypeModel used to serialize/deserialze.

To reduce the need of try{}catch{} blocks it would be great to filter out already supported types before adding them to the RuntimeTypeModel. The readme only offers a "vague" list types that are supported by default and the method Model.GetTypes() only returns a list of types that are manually added to the current model.

Readme: https://github.com/mgravell/protobuf-net

I'm using protobuf-net 2.4.0

So I'm wondering if there is any easy way to check if a type is already supported by the current RuntimeTypeModel? Currently I'm using something like this to prefilter types:

    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<>)
    };

回答1:


Try:

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


来源:https://stackoverflow.com/questions/54177121/protobuf-net-list-supported-types

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