Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

protobuf-net - list supported types

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<>)
    };
like image 834
M. Altmann Avatar asked Oct 26 '25 06:10

M. Altmann


1 Answers

Try:

 ProtoBuf.Meta.RuntimeTypeModel.Default.CanSerialize(Type type)
like image 107
Marc Gravell Avatar answered Oct 28 '25 20:10

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!