为什么需要"集合和枚举"? 使用带有 "Flags" 属性的 Bit Field 枚举存储 "个人" 拥有的 "证书" 有什么问题吗?这实际上只是选项1的更清晰版本。
根据您的评论,以下是一个非常简单的示例:
class Person
{
public string Name;
public Certifications Certifications;
}
[Flags]
enum Certifications : int
{
A = 1,
B = 2,
C = 4,
D = 8,
E = 16,
F = 32,
G = 64,
H = 128,
I = 256
};
static void Main()
{
Person a = new Person() { Name = "rob", Certifications = Certifications.A | Certifications.D | Certifications.G };
Person b = new Person() { Name = "jeb", Certifications = Certifications.B | Certifications.C | Certifications.I };
DisplayPerson(a);
DisplayPerson(b);
Console.WriteLine();
DisplayPersonInfo( a );
DisplayPersonInfo( b );
}
static IEnumerable<string> GetCerts( Person person )
{
foreach( Certifications cert in Enum.GetValues( typeof( Certifications ) ) )
{
if( PersonHasCert( person, cert ) )
yield return ( Enum.GetName( typeof( Certifications ), cert ) );
}
}
static bool PersonHasCert( Person person, Certifications cert )
{
return ( ( cert & person.Certifications ) == cert );
}
static void DisplayPersonInfo( Person p )
{
Console.WriteLine
(
String.Format
(
"Name: {0}, Certifications: {1}",
p.Name,
String.Join( ", ", GetCerts( p ) )
)
);
}
static void DisplayPerson(Person p)
{
Console.WriteLine
(
String.Format
(
"Name: {0}, Certifications: {1}",
p.Name,
p.Certifications
)
);
}
输出:
姓名:rob,认证:A、D、G
姓名:jeb,认证:B、C、I
姓名:rob,认证:A、D、G
姓名:jeb,认证:B、C、I
上述“[Flags]”属性帮助编译器知道您正在使用此数据结构并显示它包含的值(在具有该属性的“Enum”的ToString()方法上使用),因此当您想要显示所有值时,您无需迭代枚举并对每个值进行位测试)。
您对使用此方法还有什么疑虑吗?它似乎非常高效和干净,完全符合您想要实现的内容。
this是一篇涵盖该主题的很好的文章。
编辑2:
更新了示例代码,包括使用两种方式实现此功能以及一些帮助程序中的辅助方法,您应该可以在应用程序中利用它们。