让我们定义一个辅助类型:
[Flags]
public enum UserAccountControl {
// values from http://support.microsoft.com/kb/305144
Script = 0x0001,
AccountDisabled = 0x0002,
HomeDirRequired = 0x0008,
Lockout = 0x0010,
PasswordNotRequired = 0x0020,
PasswordCantChange = 0x0040,
EncryptedTextPasswordAllowed = 0x0080,
TempDuplicateAccount = 0x0100,
NormalAccount = 0x0200,
InterDomainTrustAccount = 0x0800,
WorkstationTrustAccount = 0x1000,
ServerTrustAccount = 0x2000,
DontExpirePassword = 0x10000,
MnsLogonAccount = 0x20000,
SmartcardRequired = 0x40000,
TrustedForDelegation = 0x80000,
Delegated = 0x100000,
UseDesKeyOnly = 0x200000,
DontReqPreauth = 0x400000,
PasswordExpired = 0x800000,
TrustedToAuthForDelegation = 0x1000000
}
您可以在int
和enum
类型之间进行转换(我假设您知道如何将这些值之一作为整数获取)。然后您可以使用按位运算符操作值,如下所示:
void manipulateUserFlags(UserAccountControl uac) {
// Set the SCRIPT flag (bitwise OR)
uac |= UserAccountControl.Script;
// Clear the ACCOUNTDISABLE flag (complement, bitwise AND)
uac &= ~UserAccountControl.AccountDisabled;
// Check for the HOMEDIR_REQUIRED flag (bitwise AND)
if((uac & UserAccountControl.HomeDirRequired) != UserAccountControl.None) {
// ...
}
// Toggle the NORMAL_ACCOUNT flag (bitwise XOR)
uac ^= UserAccountControl.NormalAccount;
// Check for several types of trust, and a required password
if((uac & UserAccountControl.WorkstationTrustAccount
& UserAccountControl.ServerTrustAccount
& ~UserAccountControl.PasswordNotRequired) != UserAccountControl.None) {
// ...
}
}
这些是同样适用于整数的按位运算符,但enum
在 C# 中建议使用类型,因为它们的类型更强。整数的按位操作在 C 或 C++ 中更有意义,因为您可以直接在条件中对整数进行测试,而且这些语言无论如何都不是强类型的。
但是,如果您打算将其作为库的一部分来实现,或者通常执行这些操作,我会考虑围绕它进行更多设计,使用几个enum
基于属性的属性来表示类似设置int ToADValue
和UserAccountControl FromADValue
方法的组。这将为您提供放置任何验证逻辑的清晰位置,并使操作这些属性的代码更具可读性。