3

我需要对我的数据多次执行此操作:

public void AddBehavior(BehaviorTypes type)
{
    if (Enum.IsDefined(typeof(BehaviorTypes), type))
    {
    switch (type)
    {
        case BehaviorTypes.render:
            return new renderable();
        break;   
    }
}

那是两个显式的函数调用和一个对象装箱/拆箱操作!这个操作对于检查枚举来说太昂贵了。有人知道更便宜的替代品吗?

4

3 回答 3

2

一个非常标准的技巧是将成员添加到指定第一个和最后一个值的枚举声明中:

enum BehaviorTypes {
    First = One,    
    One = 1,
    Two,
    Three,
    Last = Three
}

现在它是一个超快的测试,大约需要一纳秒:

public void AddBehavior(BehaviorTypes type)
{
    if (type >= BehaviorTypes.First && type <= BehaviorTypes.Last) {
       // etc..
    }
}

请注意,您的 switch 语句已经消除了此检查的需要。

于 2012-07-27T12:04:12.367 回答
1

您可以使用 Enum.GetValues 在优化的集合中、在静态成员中一劳永逸地提取枚举类型的所有现有值。接下来您只需搜索该集合。

我猜如果只考虑一个枚举,最快的将是一组布尔值,告诉你你的积分是否存在于枚举中。除了这个数组的构造(成本一次),你将有一个 enum 到 int 的转换,以及一个数组中的读取访问(如果我没记错的话,这是你能得到的最快的?)。

于 2012-07-27T10:08:40.970 回答
1

关于 .NET 的一个鲜为人知的事实是,您可以在枚举上声明扩展方法。避免拳击将是这样做的一个很好的理由。为了便于维护,您可以在与枚举相同的文件中定义静态方法,以便您知道同时更改它们。

public enum BehaviorTypes
{
    Render,
    Foo,
    Bar
}

public static class BehaviorTypesExtensions
{
    public static bool IsDefined(this BehaviorTypes behaviorTypes)
    {
        return behaviorTypes >= BehaviorTypes.Render && behaviorTypes <= BehaviorTypes.Bar;
    }
}

用法

class Program
{
    static void Main(string[] args)
    {
        foreach (BehaviorTypes value in Enum.GetValues(typeof(BehaviorTypes)))
        {
            Console.WriteLine($"{value} is defined: {value.IsDefined()}");
        }

        Console.WriteLine($"43 is defined: {((BehaviorTypes)43).IsDefined()}");

        // Render is defined: True
        // Foo is defined: True
        // Bar is defined: True
        // 43 is defined: False
    }
}
于 2021-04-09T23:58:18.343 回答