简体   繁体   English

C#访问具有继承的修饰符

[英]C# Access Modifiers with Inheritance

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? 这是我可以实现的,还是我必须以更加程序化的方式控制访问?

Is inheritance really the right fit here? 遗产真的适合这里吗? Users of the UserInfo class shouldn't need to be aware of the subtypes. UserInfo类的用户不需要知道子类型。 In this case, users would need to know that the Password property is somehow unavailable when given a ReadUserInfo instance rather than a UserInfo instance. 在这种情况下,当给定ReadUserInfo实例而不是UserInfo实例时,用户需要知道Password属性在某种程度上不可用。

This really doesn't make sense. 这真的没有意义。

Edit: In OO design, this is known as the Liskov Substitution Principle 编辑:在OO设计中,这被称为Liskov替换原则

you can use the new modifier: 你可以使用new修饰符:

public class ReadUserInfo : UserInfo
{
    internal ReadUserInfo()
    {
    }
    new public int ID { get; internal set; }
    new internal string Password { get; set; }
    new public string Username { get; internal set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM