C# Flags特性的使用案例


现在有这么一个需求:

生成随机长度的一个字符串,要求可以包含大写字母或者小写字母,或者数字,这三种排列组合都可以

效果如下

后台代码

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Collections.ObjectModel;
  4 using System.Linq;
  5 using System.Text;
  6 using System.Threading.Tasks;
  7 using System.Windows;
  8 using System.Windows.Controls;
  9 using System.Windows.Data;
 10 using System.Windows.Documents;
 11 using System.Windows.Input;
 12 using System.Windows.Media;
 13 using System.Windows.Media.Imaging;
 14 using System.Windows.Shapes;
 15 
 16 namespace MvvmToolkit学习
 17 {
 18     /// 
 19     /// 字符类型
 20     /// 
 21     [Flags]
 22     public enum CharacterType
 23     {
 24         /// 
 25         /// 无内容
 26         /// 
 27         None = 0,
 28 
 29         /// 
 30         /// 小写字母
 31         /// 
 32         LowercaseEnglish = 1,
 33 
 34         /// 
 35         /// 大写字母
 36         /// 
 37         UppercaseEnglish = 2,
 38 
 39         /// 
 40         /// 数字
 41         /// 
 42         Number = 4,
 43     }
 44 
 45     public class SelectItem
 46     {
 47         public CharacterType CharacterType { get; set; }
 48         public bool IsSelected { get; set; }
 49     }
 50 
 51     /// 
 52     /// RandomCharacter.xaml 的交互逻辑
 53     /// 
 54     public partial class RandomCharacter : Window
 55     {
 56         /// 
 57         /// 小写英文字符
 58         /// 
 59         public const string LowercaseEnglishCharacters = "abcdefghijklmnopqrstuvwxyz";
 60 
 61         /// 
 62         /// 数字字符
 63         /// 
 64         public const string NumberCharacters = "0123456789";
 65 
 66         /// 
 67         /// 大写英文字符
 68         /// 
 69         public const string UppercaseEnglishCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 70 
 71         private ObservableCollection SelectItems { get; set; }
 72 
 73         public RandomCharacter()
 74         {
 75             InitializeComponent();
 76             //填入数据
 77             SelectItems = new ObservableCollection();
 78             var list = Enum.GetNames(typeof(CharacterType))
 79                 .Select(e => new SelectItem() { CharacterType = (CharacterType)Enum.Parse(typeof(CharacterType), e), IsSelected = true });
 80             EnumTypeListBox.ItemsSource = SelectItems;
 81             foreach (var item in list)
 82             {
 83                 SelectItems.Add(item);
 84             }
 85         }
 86 
 87         /// 
 88         /// 随机字符串
 89         /// 
 90         /// 字符串长度
 91         /// 组成字符串的字符类型
 92         /// 
 93         /// 
 94         public static string GenerateRandomCharacters(int length, CharacterType characterType)
 95         {
 96             var list = new List<char>();
 97 
 98             if (characterType == CharacterType.None)
 99             {
100                 throw new ArgumentException("参数错误");
101             }
102             //判断传入的参数是否包含特定枚举
103             if (characterType.HasFlag(CharacterType.LowercaseEnglish))
104             {
105                 list.AddRange(LowercaseEnglishCharacters.ToList());
106             }
107             if (characterType.HasFlag(CharacterType.UppercaseEnglish))
108             {
109                 list.AddRange(UppercaseEnglishCharacters.ToList());
110             }
111             if (characterType.HasFlag(CharacterType.Number))
112             {
113                 list.AddRange(NumberCharacters.ToList());
114             }
115 
116             var builder = new StringBuilder();
117             var random = new Random();
118             for (int i = 0; i < length; i++)
119             {
120                 var index = random.Next(list.Count);
121                 builder.Append(list[index]);
122             }
123             return builder.ToString();
124         }
125 
126         private void Generate(object sender, RoutedEventArgs e)
127         {
128             //获取所有选择的类型
129             var values = SelectItems.Where(s => s.IsSelected)
130                 .Select(s => s.CharacterType)
131                 .Aggregate((x, y) => x | y);
132 
133             DisplayTextBlock.Text = GenerateRandomCharacters(10, values);
134         }
135     }
136 
137   
138 }

界面代码

 1 <Window
 2     x:Class="MvvmToolkit学习.RandomCharacter"
 3     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 4     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 5     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 6     xmlns:local="clr-namespace:MvvmToolkit学习"
 7     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 8     Title="RandomCharacter"
 9     Width="800"
10     Height="450"
11     mc:Ignorable="d">
12     
13         "Vertical">
14             <ListBox
15                 DataContext="{Binding SelectItems}"
16                 x:Name="EnumTypeListBox"
17                 Width="200">
18                 
19                     
20                         "Horizontal">
21                             "{Binding IsSelected}" Content="{Binding CharacterType}"/>
22                         
23                     
24                 
25             
26             <TextBlock
27                 x:Name="DisplayTextBlock"
28                 FontSize="20"
29                 HorizontalAlignment="Center"
30                 VerticalAlignment="Center"
31                 Foreground="Red"
32                 Width="200"
33                 Height="50"/>
34             <Button
35                 Width="200"
36                 Height="50"
37                 Click="Generate"/>
38         
39     
40 

看起来简单又方便