这是一个标志有用的例子。
我有一段代码可以生成密码(使用密码安全的伪随机数生成器)。该方法的调用者选择密码是否应包含大写字母,小写字母,数字,基本符号,扩展符号,希腊符号,西里尔字母和unicode。
使用标志,调用此方法很容易:
var password = this.PasswordGenerator.Generate(
CharacterSet.Digits | CharacterSet.LowercaseLetters | CharacterSet.UppercaseLetters);
甚至可以简化为:
var password = this.PasswordGenerator.Generate(CharacterSet.LettersAndDigits);
没有标志,方法签名是什么?
public byte[] Generate(
bool uppercaseLetters, bool lowercaseLetters, bool digits, bool basicSymbols,
bool extendedSymbols, bool greekLetters, bool cyrillicLetters, bool unicode);
这样称呼:
// Very readable, isn't it?
// Tell me just by looking at this code what symbols do I want to be included?
var password = this.PasswordGenerator.Generate(
true, true, true, false, false, false, false, false);
如评论中所述,另一种方法是使用集合:
var password = this.PasswordGenerator.Generate(
new []
{
CharacterSet.Digits,
CharacterSet.LowercaseLetters,
CharacterSet.UppercaseLetters,
});
与true
和相比,它更具可读性false
,但仍然有两个缺点:
主要缺点是,为了允许组合值,就像CharacterSet.LettersAndDigits
您在Generate()
方法中编写类似的代码一样:
if (set.Contains(CharacterSet.LowercaseLetters) ||
set.Contains(CharacterSet.Letters) ||
set.Contains(CharacterSet.LettersAndDigits) ||
set.Contains(CharacterSet.Default) ||
set.Contains(CharacterSet.All))
{
// The password should contain lowercase letters.
}
可能是这样重写的:
var lowercaseGroups = new []
{
CharacterSet.LowercaseLetters,
CharacterSet.Letters,
CharacterSet.LettersAndDigits,
CharacterSet.Default,
CharacterSet.All,
};
if (lowercaseGroups.Any(s => set.Contains(s)))
{
// The password should contain lowercase letters.
}
通过使用标志将其与您所拥有的进行比较:
if (set & CharacterSet.LowercaseLetters == CharacterSet.LowercaseLetters)
{
// The password should contain lowercase letters.
}
第二个非常小的缺点是,尚不清楚如果这样调用,该方法将如何表现:
var password = this.PasswordGenerator.Generate(
new []
{
CharacterSet.Digits,
CharacterSet.LettersAndDigits, // So digits are requested two times.
});