本文介绍了派生类的可访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要在C#中是不允许的派生类具有比其基类更高的可访问性。

Why in C# it is not allowed for derived classes to have greater accessibility than its base class.

例如这会给错误:可访问性不一致:基类BaseClass的比类DerivedClass

For example this will give error : Inconsistent accessibility: base class 'BaseClass' is less accessible than class 'DerivedClass'

internal class BaseClass
{
}

public class DerivedClass : BaseClass
{
}

和为什么它是允许Java编写的。

And why it is allowed in Java.

推荐答案

更新:这个问题问得我的博客上二〇一二年十一月十三日的主题。感谢伟大的问题!

UPDATE: This question was the subject of my blog on November 13th 2012. Thanks for the great question!

为什么要在C#中是不允许的派生类具有比其基类更容易获得?

在除了其他好的答案,考虑此方案。你和你的同事爱丽丝正在使用的同一总成的不同部分。爱丽丝写一个类:

In addition to the other good answers, consider this scenario. You and your coworker Alice are working on different parts of the same assembly. Alice writes a class:

public class ComplicatedClass
{
    public void DoDangerousThing() { ... }
}

您接着写

public class EvenMoreComplicatedClass : ComplicatedClass
{
}

大。现在,爱丽丝会从鲍勃安全审查,他们认识到,(1)没有客户永远需要使用ComplicatedClass,和(2)DoDangerousThing公开敌对code可以利用的安全漏洞。当然,内部code没有。

Great. Now Alice gets a security review from Bob, and they realize that (1) no customer ever needs to use ComplicatedClass, and (2) DoDangerousThing exposes a security hole that hostile code could take advantage of. Internal code of course does not.

于是,爱丽丝改变了她的code到

So Alice changes her code to

internal class ComplicatedClass
{
    public void DoDangerousThing() { ... }
}

搞清楚有没有必要改变公到内部的,因为当然是公开的方法,意思是大众的事情,可以看到这班,现在无需外接code可以看到这个类。

Figuring there is no need to change "public" to "internal" on the method because of course public means "public to things that can see this class", and now no external code can see this class.

我应该发生在你的code当爱丽丝重新编译这种变化? 它应该编译失败。你已经做了,用户需要看到基类的假设,爱丽丝取得了违反这一假设的变化。安全的做法是让编译器告诉爱丽丝,她需要再来说说你,让你能解决这个问题,而不会让客户DoDangerousThing的脆弱性。

What should happen to your code when Alice recompiles with this change? It should fail to compile. You have made an assumption that users need to see the base class, and Alice has made a change that violates that assumption. The safe thing to do is for the compiler to tell Alice that she needs to come talk to you so that you can resolve this problem without exposing the customer to the vulnerability of DoDangerousThing.

为什么允许它在Java中?

不知道,不好意思。

这篇关于派生类的可访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:16