1

尝试随机化枚举值。问题是枚举位于我在代码中引用的参考文件中。例如

        public enum AccountTypeEnum
{
        Direct,
        Partner,
        Referral,
        Resold,
}

在我的参考文件和我的代码中,我需要引用 AccountTypeEnum 并将其随机化,因此当我运行我的程序时,我可以获得这 4 个值之一。

到目前为止,我认为随机化这些值是这样的:

   public void AcctType()
        {
            string[] Types = Enum.GetNames(typeof(AccountTypeEnum));            
            Random randType = new Random();
            int randomenum = randType.Next(Types.Length);
            var ret = Enum.Parse(typeof(AccountTypeEnum), Types[randomenum]);
        }

关于我做错了什么有什么建议吗?

4

1 回答 1

1

弄清楚了。创建了一个新类:

public class EnumRandomizeer
{
    public static Random rand = new Random();
    public static T GetRandomValue<T>()
    {
        T[] values = (T[])(Enum.GetValues(typeof(T)));
        return values[rand.Next(0, values.Length)];
    }
}

当引用枚举值时,我引用了这样的类:

 AccountTypeEnum randomAcct = EnumRandomizeer.GetRandomValue<AccountTypeEnum>();

工作得很好!

于 2013-02-04T20:52:44.017 回答