我有一种简单的方法可以从我的枚举变量中选择一个随机位值吗? 例如:
[System.Flags]
public enum Direction{
None = 0,
Up = 1,
Down = 2,
Left = 4,
Right = 8,
All = ~None
}
public Direction someDir = Direction.Up | Direction.Down;
我想从someDir
中选择一个随机正位值,以便我只能Direction.Up
或Direction.Down
?
答案 0 :(得分:2)
您应该使用数组:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
//
//XXX Si se usa implicit descomentar
.ignoringAntMatchers("/oauth/authorize")
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic()
然后:
Direction validDirections = new[] { Direction.Up, Direction.Down };
(请记住重复使用相同的Random rnd = new Random();
Direction selectedDirection = validDirections[rnd.Next(validDirections.Length)];
而不是每次都重新创建它)
如果您真的想要一个Random rnd
变量,那么您可以将其拆分为Direction
:
List<Direction>
(请参阅Most efficient way to parse a flagged enum to a list以及有关使用Direction someDir = Direction.Up | Direction.Down;
var someDir2 = new List<Direction>();
foreach (Direction dir in Enum.GetValues(typeof(Direction)))
{
if (someDir.HasFlag(dir))
{
someDir2.Add(dir);
}
}
Random rnd = new Random();
Direction selectedDirection = someDir2[rnd.Next(someDir2.Count)];
)的各种评论