Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enabling EnumPassthru by default

Tags:

protobuf-net

Quick question, is it possible to enable to EnumPassthru by default on all enum types? At the moment I have to enable this on each enum type manually or use the following method to apply it automatically to my DTO assembly types:

    public static void ConfigureEnumTypes(RuntimeTypeModel tm, Assembly a)
    {
        foreach (var type in a.GetTypes())
        {
            if (type.IsEnum && type.GetCustomAttribute<ProtoContractAttribute>() != null)
                tm[type].EnumPassthru = true;
        }
    }

If there is a better way, I'd like to know. Thanks.

like image 611
Barguast Avatar asked Jun 21 '13 22:06

Barguast


1 Answers

This passes in the next build:

[TestFixture]
public class SO17245073
{
    [Test]
    public void Exec()
    {
        var model = TypeModel.Create();
        Assert.IsFalse(model[typeof(A)].EnumPassthru, "A");
        Assert.IsTrue(model[typeof(B)].EnumPassthru, "B");

        Assert.IsFalse(model[typeof(C)].EnumPassthru, "C");
        Assert.IsTrue(model[typeof(D)].EnumPassthru, "D");

        Assert.IsTrue(model[typeof(E)].EnumPassthru, "E");
        Assert.IsTrue(model[typeof(F)].EnumPassthru, "F");

        Assert.IsFalse(model[typeof(G)].EnumPassthru, "G");
        Assert.IsFalse(model[typeof(H)].EnumPassthru, "H");            
    }

    // no ProtoContract; with [Flags] is pass-thru, else not
    public enum A { X, Y, Z }
    [Flags]
    public enum B { X, Y, Z }

    // basic ProtoContract; with [Flags] is pass-thru, else not
    [ProtoContract]
    public enum C { X, Y, Z }
    [ProtoContract, Flags]
    public enum D { X, Y, Z }

    // ProtoContract with explicit pass-thru enabled; always pass-thru
    [ProtoContract(EnumPassthru = true)]
    public enum E { X, Y, Z }
    [ProtoContract(EnumPassthru = true), Flags]
    public enum F { X, Y, Z }

    // ProtoContract with explicit pass-thru disabled; never pass-thru
    // (even if [Flags])
    [ProtoContract(EnumPassthru = false)]
    public enum G { X, Y, Z }
    [ProtoContract(EnumPassthru = false), Flags]
    public enum H { X, Y, Z }
}

From your example code here:

if (type.IsEnum && type.GetCustomAttribute<ProtoContractAttribute>() != null)

it sounds like all you should need to do, since you already have [ProtoContract], is to make that [ProtoContract(EnumPassthru = true)] on your enum declarations.

like image 70
Marc Gravell Avatar answered Sep 27 '22 19:09

Marc Gravell