实例化所有可能的枚举组合 [英] Instantiating all possible combinations of enums

查看:268
本文介绍了实例化所有可能的枚举组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法迭代所有可能的枚举组合。我不太熟悉他们,因为我刚刚开始C#,并从低级语言如C和汇编进来。

I'm having trouble iterating over all possible combinations of enums. I'm not too familiar with them as I've just started C# and am coming in from low level languages like C and assembler.

public enum enumA { A1, A2, A3 }
public enum enumB { B1, B2, B3 }

public class foo
{
    private enumA enumAfoo;
    private enumB enumBfoo;

    public foo()
    {
    }
    public foo(enumA A, enumB B)
    {
        enumAfoo = A;
        enumBfoo = B;
    }
}

public class fooTwo
{
    private List<foo> allCombinations = new List<foo>();
    public fooTwo()
    {

    }
    public List<foo> GetList()
    {
        return allCombinations;
    }
    public fooTwo(bool check)
    {
        if (check)
        {
            foreach (enumA i in Enum.GetValues(typeof(enumA)))
            {
                foreach (enumB j in Enum.GetValues(typeof(enumB)))
                {
                    allCombinations.Add(new foo(i, j));
                }
            }
        }
    }
}


$ b b

当我在一个简单的检查输出中运行这个代码,我不会得到我的后。下面的示例主。我得到的输出只是TestingGround.foo重复6次,测试地面是我的整体命名空间。我不知道我的逻辑实例化列表有问题,或者我如何将其转换为字符串和输出,但我非常想要一些帮助,这是正确的程序这样做。

When I run this code in a simple check output, I don't get what I'm after. Sample Main below. The output I get is just "TestingGround.foo" repeated 6 times, testing ground being my overall namespace. I Don't know if there's a problem with my logic of instantiating the list, or with how I'm converting it to string and outputting but I'd very much like some help in what's the correct procedure for doing this.

class Program
{
    static void Main(string[] args)
    {
        fooTwo A = new fooTwo(true);
        List<foo> list = A.GetList();
        foreach (foo j in list)
        {
            Console.WriteLine(j.ToString());
        }
        Console.ReadKey();
    }
}


推荐答案

ToString ()返回对象的默认表示。你需要创建自己的ToString()方法,返回你所需要的。例如:

ToString() returns a default representation of the object. You need to create your own ToString() method, returning what you need. For example:

public class foo
{
    private enumA enumAfoo;
    private enumB enumBfoo;

    public foo()
    {
    }
    public foo(enumA A, enumB B)
    {
        enumAfoo = A;
        enumBfoo = B;
    }
    public override string ToString()
    {
        return enumAfoo.ToString() + "," + enumBfoo.ToString();
    }
}

这篇关于实例化所有可能的枚举组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆