你的问题的核心是你似乎试图使用接口来描述一个类是什么,而不是它的功能。接口最好用于指定 IAuthorizeable 或 IEnumerable 等内容。它们表明在一个共同主题上的不同行为。
对于像您这样的情况,正如其他人所建议的那样,您希望使用继承,除非您可以更改构建事物的方式。我的偏好是创建一个包含不同部分策略的用户类,而不是继承。
继承共享功能和允许差异可扩展之间存在很大差异。如果你用接口编写User而不是创建基类,如果将来需要添加更多角色,你只需要添加改变行为的另一个实现,而不是创建另一个可能与另一个共享不同事物的子类两个班。
一个例子:
class User
{
private IAuthenticator authenticator;
public string Name { get; set; }
public Guid Id { get; set; }
public User(string name, Guid id, IAuthenticator authenticator)
{
Name = name;
Id = id;
this.authenticator = authenticator;
}
public Rights Authenticate()
{
return authenticator.Authenticate(Name, Id);
}
}
身份验证器可能是这样的:
public class WebAuthenticator : IAuthenticator
{
public Rights Authenticate(string name, Guid id)
{
// Some web specific authentication logic
}
}
和权利:
[Flags]
public enum Rights
{
None = 0, Read = 1, Write = 1 << 1, Execute = 1 << 2
}
最终结果是您的代码可重用、可扩展且灵活。一般来说,用户是管理员这一事实不应该给用户类额外的逻辑,而是限制使用特定实例的东西。