【问题标题】:Is there anyway to make a variable "partially protected"?无论如何要使变量“部分保护”?
【发布时间】:2014-01-16 05:16:21
【问题描述】:

我有以下类层次结构

 public class Third : Second
{
}

public class Second : First
{
}

public class First
{
     private int MyVariable;
}

如果我想从 Second 和 Third 访问 MyVariable,我可以使 MyVariable 受到保护,但如果我想从 Second 而不是 Third 访问怎么办。这可能吗?

【问题讨论】:

  • 你能举个例子吗?
  • 仅当您使用 new 关键字隐藏它时。无论如何,说实话,这不是我见过的最好的面向对象实践。
  • 您是否考虑过构图是一种选择?
  • 考虑将您的 First 类抽象化,然后只在需要它的类中实现 MyVariable。

标签: c# variables inheritance protected


【解决方案1】:

如果我想从SecondThird 访问MyVariable,我可以使MyVariable 受保护。如果我想从Second 访问而不是Third 怎么办。这可能吗?

是的!这是一种技术:

class First
{
    private int myVariable;
    public class Second : First
    {
        public Second() { myVariable = 123; } // Legal!
    }
}

class Third : First.Second
{
    public Third() { myVariable = 456; } // Illegal!
}

这是另一个:

// Alpha.DLL
public class First 
{ 
    internal int myVariable;
}
public class Second : First
{
    public Second() { myVariable = 123; } // Legal!
}

// Bravo.DLL
class Third : Second
{
    public Third() { myVariable = 456; } // Illegal!
}

【讨论】:

    【解决方案2】:

    您没有以面向对象的方式考虑这一点。

    您声明每个Third 都是Second。但是您希望每个Second 都可以访问该变量,但您不希望任何Third 都可以访问。

    但如果Third没有访问权限,那么它就不是Second

    【讨论】:

    • 那你怎么解释我的例子?
    • 我还不能。我得考虑一下。私有实现细节不需要为了多态工作而被继承。
    • 您误用了 Liskov 替换原则,即“如果 q(x) 是关于所有类型为 Base 的对象 x 的事实,那么 q(y) 应该是关于所有对象 y 的事实类型派生”。您正在为谓词 q(z) “z 有权访问该字段”提出建议。但是谓词必须是关于对象的谓词!该谓词是关于源代码区域,而不是关于在运行时生成的对象
    • @EricLippert:唠叨,唠叨,唠叨。 :-)
    • 不违反 LSP 意味着 Eric 的解决方案不会让那些使用 First 而不知道存在 SecondThird 的人遇到困难。也就是说,它不太可能是消耗First 实例的类中的错误的原因。他们给我的印象是解决大多数人(可能包括 OP)通常没有的问题的绝佳解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多