2

假设我有一个枚举标志:

[Flags]
public enum ColorType
{
    None = 0,
    Red = 1 << 0,
    White = 1<<1,
    Yellow = 1 << 2,
    Blue = 1 << 3,
    All = Red | White | Yellow | Blue
}

我有以下函数,该参数是标志的组合,例如 DoSomething( ColorType.Blue | ColorType.Yellow )。

public void DoSomethingr(ColorType theColorTypes)
{
        if (theColorTypes.HasFlag(All)) Foo1();
        if (theColorTypes.HasFlag(White) && theColorTypes.HasFlag(Red) )  Foo2();
        if (!theColorTypes.HasFlag(Blue)) Foo3();
        . . . 
}

有没有一种简单的方法来测试所有可能的标志位组合?

[Test] 
public void Test1(ColorType.Red | ColorType.Yellow | ColorType.White) 

[Test]
public void Test1(ColorType.Red | ColorType.Yellow | ColorType.white | ColorType.Blue) 

谢谢

4

2 回答 2

1

循环所有可能的值并将其放入 aTestCaseSource为每个枚举值生成不同的测试:

public IEnumerable<ColorType> TestCaseSource 
{ 
    get
    {
        int start = (int)ColorType.None;
        int count = (int)ColorType.All - start + 1;
        return Enumerable.Range(start, count).Select(i => (ColorType)i); 
    } 
}

[TestCaseSource("TestCaseSource")]
public void Test1(ColorType colorType)
{
    // whatever your test is
}
于 2014-10-14T20:52:36.313 回答
0

只是我的两分钱,这可能会被改进以接受“其他”值类型,但是当您喜欢扩展方法时,作为替代方法:

public static class EnumExtensions
{
    public static bool HasFlags<TEnum>(this TEnum @enum,
                                       TEnum flag,
                                       params TEnum[] flags)
        where TEnum : struct
    {
        var type = typeof(TEnum);
        if (!type.IsEnum)
            throw new ArgumentException("@enum is not an Enum");

        var hasFlagsMethod = type.GetMethod("HasFlag");
        var hasFlag = new Func<TEnum, bool>(e =>
        {
            return (bool)hasFlagsMethod.Invoke(@enum, new object[] { e });
        });

        // test the first flag argument
        if (!hasFlag(flag))
            return false;

        // test the params flags argument
        foreach (var flagValue in flags)
        {
            if (!hasFlag(flagValue))
                return false;
        }
        return true;
    }
}


[Flags]
public enum ColorType
{
    None = 0,
    Red = 1 << 0,
    White = 1 << 1,
    Yellow = 1 << 2,
    Blue = 1 << 3,
    All = Red | White | Yellow | Blue
}

像这样称呼它:

class Program
{
    static void Main(string[] args)
    {
        var color = ColorType.Red;
        Console.WriteLine(color.HasFlags(ColorType.Red)); // true;
        Console.WriteLine(color.HasFlags(ColorType.Red, ColorType.Blue)); // false;

        color = ColorType.All;
        Console.WriteLine(color.HasFlags(ColorType.Red, ColorType.Blue)); // true;

        Console.ReadLine();
    }
}
于 2014-10-14T21:33:17.843 回答