如何在c#中限制基类成员对不同子类的访问 [英] how to restrict the access of members of a base class to different child classes in c#

查看:278
本文介绍了如何在c#中限制基类成员对不同子类的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个A类,有3种方法M1,M2,M3。

B类继承自A类,C类继承自B类。



现在A类的所有方法都可以用于B类和C类。



现在我想限制

1)B级的A级M1和M2

2)C级的M3。



我该怎么办?

I have a class A with 3 methods M1,M2,M3.
Class B is inherited from Class A & Class C is inherited from Class B.

Now all the methods in Class A are accessible for Class B & Class C.

Now i want to restrict
1)M1 & M2 of Class A for Class B
2)M3 for Class C .

How can i do this.

推荐答案

你不能。你不应该,即使有可能。没有意义 - 你为什么要那样做?如果M1和M2特定于B和M3特定于C,则在B中实现M1和M2,在C中实现M3。



这将违反多态性 [ ^ ]:如果像基类一样使用它,子类应该像基类一样。如果B级无法访问M3,那么你将无法像A级一样使用它。
You can't. And you shouldn't, even if it was possible. It makes no sense - why would you want to do that? If M1 and M2 are specific to B and M3 specific to C, then implement M1 and M2 in B and M3 in C.

It would violate the principle of polymorphism[^]: A subclass should behave like the baseclass if it is being used like the baseclass. If a B-class doesn't have access to M3 then you wouldn't be able to use it like an A-class.


这篇关于如何在c#中限制基类成员对不同子类的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆