Question

I have a class that defines constants for my design. For example the following :

public static class ObjectTypes
{
    /// <summary>
    /// The identifier for the ConfigurableObjectType ObjectType.
    /// </summary>
    public const uint ConfigurableObjectType = 2;

    /// <summary>
    /// The identifier for the FunctionalGroupType ObjectType.
    /// </summary>
    public const uint FunctionalGroupType = 4;

    /// <summary>
    /// The identifier for the ProtocolType ObjectType.
    /// </summary>
    public const uint ProtocolType = 5;
}

Now in my code I have calculated and integer value for.eg valueInt and I would like to compare valueInt with all the constants defined in this class. Is there a quick way to do it without using If-then-else blocks or switch case because in case there are a large number of constants this kind of an approach will result in a large code. Is a better approach somehow possible? I am working in C#.

Note : I cannot change the design for the above mentioned class as I get such a class predefined for e.g from a library or a class designed by someone else which I cannot change but I should only refer to in my code.

Était-ce utile?

La solution

Could use reflection. Should test to make sure it doesn't perform unacceptably for you though.

    private static bool IsDefined(uint i) {
        var constants = typeof(ObjectTypes).GetFields().Where(f => f.IsLiteral).ToArray();

        foreach(var constant in constants) {
            if(i == (uint)constant.GetRawConstantValue()) {
                return true;
            }
        }

        return false;
    }

Autres conseils

Although not a pretty construct, to give a possible solution for the given problem without changing existing code.

The following code uses reflection to compare

        string fieldName = "not found";
        uint testValue = 5;

        Type t = typeof(ObjectTypes);
        FieldInfo[] f = t.GetFields();
        Array.ForEach<FieldInfo>(f, (info) => { if (testValue == (uint)info.GetValue(null)) fieldName = info.Name; });

and yields "ProtocolType" at the end of the code.

Hope this helps,

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top