具有继承性的 C# 访问修饰符
我想要一个对象的多个版本,在属性上具有不同的访问修饰符
例如,我可能有一个用户类 -
public abstract class UserInfo
{
internal UserInfo()
{
}
public virtual int ID { get; set; }
public virtual string Password { internal get; set; }
public virtual string Username { get; set; }
}
public class ReadUserInfo : UserInfo
{
internal ReadUserInfo()
{
}
override public int ID { get; internal set; }
override internal string Password { get; set; }
override public string Username { get; internal set; }
}
public class NewUserInfo : UserInfo
{
internal NewUserInfo()
{
ID = -1;
}
//You get the Idea
}
这是我可以实现的东西还是我必须以更编程的方式控制访问?
I'd like to have multiple versions of an object with different access modifiers on the properties
For example I might have a user class-
public abstract class UserInfo
{
internal UserInfo()
{
}
public virtual int ID { get; set; }
public virtual string Password { internal get; set; }
public virtual string Username { get; set; }
}
public class ReadUserInfo : UserInfo
{
internal ReadUserInfo()
{
}
override public int ID { get; internal set; }
override internal string Password { get; set; }
override public string Username { get; internal set; }
}
public class NewUserInfo : UserInfo
{
internal NewUserInfo()
{
ID = -1;
}
//You get the Idea
}
Is this something I can implement or do I have to control access in a more programmatic fashion?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
继承真的适合这里吗?
UserInfo
类的用户不需要了解子类型。在这种情况下,用户需要知道,当给定ReadUserInfo
实例而不是UserInfo
实例时,Password
属性在某种程度上不可用。这确实没有道理。
编辑:在面向对象设计中,这被称为里氏替换原则
Is inheritance really the right fit here? Users of the
UserInfo
class shouldn't need to be aware of the subtypes. In this case, users would need to know that thePassword
property is somehow unavailable when given aReadUserInfo
instance rather than aUserInfo
instance.This really doesn't make sense.
Edit: In OO design, this is known as the Liskov Substitution Principle
您可以使用新的修饰符:
you can use the new modifier: