我有以下类改变某个查询的结果:
public class UniversalPrincipalQueryOptions
{
public Boolean IncludeProperties { get; set; }
public Boolean IncludeOrganizationUnits { get; set; }
public Boolean IncludeManagers { get; set; }
public static UniversalPrincipalQueryOptions All
{
get
{
return new UniversalPrincipalQueryOptions { IncludeOrganizationUnits = true, IncludeProperties = true, IncludeManagers = true };
}
}
public static UniversalPrincipalQueryOptions None
{
get
{
return new UniversalPrincipalQueryOptions { IncludeProperties = false };
}
}
public UniversalPrincipalQueryOptions()
{
this.IncludeProperties = true;
}
}
问题是,IncludeOrganizationUnits
true
IncludeProperties
false
IncludeManagers
在我的情况下没有意义,IncludeOrganizationUnits
也是如此在true
设置为enum
。
我认为这不是最好的方法。所以我的问题是,我可以用什么模式来改进这个类,让其他人更容易使用我的类?
更新:
好的,所以我最后切换到用Flags
属性修饰的[Flags]
public enum UniversalPrincipalQueryOptions
{
None = 0,
IncludeProperties = 1,
IncludeOrganizationUnits = 2 | IncludeProperties,
IncludeManagers = 4 | IncludeOrganizationUnits
}
:
{{1}}
答案 0 :(得分:2)
简单的答案是验证值而不是纯自动属性:
public Boolean IncludeProperties { get; set; }
private Boolean includeOrganizationUnits;
public Boolean IncludeOrganizationUnits
{
get { return this.includeOrganizationUnits }
set
{
if(value && !IncludeProperties)
throw new InvalidOperationException("IncludeProperties must be true when IncludeOrganizationUnits is set to true");
includeOrganizationUnits = value;
}
}
也可以使用CodeContracts配置此类前置条件,但请注意有performance hit by doing so。
另一个选择,如果用户实际上不需要自己设置布尔值,那就是扩展静态列表以包含所有(有效)可能性并使事物变得私有(如setter和ctor):
public class UniversalPrincipalQueryOptions
{
public Boolean IncludeProperties { get; private set; }
public Boolean IncludeOrganizationUnits { get; private set; }
public Boolean IncludeManagers { get; private set; }
// UPDATED !!
public static UniversalPrincipalQueryOptions OrganizationUnitsAndManagers
{
get
{
return new UniversalPrincipalQueryOptions { IncludeOrganizationUnits = true, IncludeProperties = true, IncludeManagers = true };
}
}
// NEW!!
public static UniversalPrincipalQueryOptions OrganizationUnits
{
get
{
return new UniversalPrincipalQueryOptions { IncludeOrganizationUnits = true, IncludeProperties = true};
}
}
public static UniversalPrincipalQueryOptions None
{
get
{
return new UniversalPrincipalQueryOptions { IncludeProperties = false };
}
}
private UniversalPrincipalQueryOptions()
{
this.IncludeProperties = true;
}
}