0

我有一个为我的设计定义常量的类。例如以下:

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

现在在我的代码中,我已经计算了.eg valueInt 的整数值,我想将 valueInt 与此类中定义的所有常量进行比较。有没有一种不使用 If-then-else 块或 switch case 的快速方法,因为如果有大量常量,这种方法将导致大量代码。以某种方式有更好的方法吗?我在 C# 中工作。

注意:我无法更改上述类的设计,因为我从库或其他人设计的类中获得了预定义的类,我无法更改但我只能在我的代码中引用。

4

2 回答 2

1

可以使用反射。应该测试以确保它不会为您执行不可接受的操作。

    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;
    }
于 2013-11-12T20:42:10.110 回答
0

虽然不是一个漂亮的构造,但在不更改现有代码的情况下为给定问题提供可能的解决方案。

下面的代码使用反射来比较

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

并在代码末尾产生“ProtocolType”。

希望这可以帮助,

于 2013-11-12T20:35:57.537 回答