如何确保只有部分子类继承自父类

编程入门 行业动态 更新时间:2024-10-25 08:27:58
本文介绍了如何确保只有部分子类继承自父类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我只希望来自主/父类的数据相应地由子类继承 我尝试了什么: 将我的变量声明为私有

I only want data from the main/parent class to be inherited by the child classes accordingly What I have tried: Declaring my variables as private

推荐答案

您无法选择哪些类可以继承基类,或者它们继承的部分除了使用私有(无访问),受保护(任何派生类),内部(仅在同一个程序集中),私有保护(派生,但必须在同一个程序集中 - c#7.2作为类/属性的访问修饰符。 虽然......有一种方法可以作弊。如果仔细编写属性/方法,如果访问类不兼容,则可以抛出运行时异常 You can't select which classes can inherit a base class, or what "parts" of it they inherit except by using private (no access), protected (any derived class), internal (only within the same assembly), private protected (derived, but must be in the same assembly - c#7.2 onward) as the access modifier for the class / properties. Though ... there is one way to cheat. If code your property / methods carefully, you can throw a runtime exception if the accessing class is not "compatible" public interface IDontThrowException { } public class IsAllowed : MyClass, IDontThrowException { } public class IsntAllowed : MyClass { }

然后在你的班级中

Then in your class

private int result = 666; public int GetIfAllowed { get { if (!(this is IDontThrowException)) throw new ApplicationException("Not allowed"); return result; } } private void MyButton_Click(object sender, EventArgs ew) { MyClass allowed = new IsAllowed(); MyClass notAllowed = new IsntAllowed(); Console.WriteLine(allowed.GetIfAllowed); // Fine Console.WriteLine(notAllowed.GetIfAllowed); // Throws an exception.

这是一种讨厌的做事方式,但......

It's a nasty way to do things, but...

更多推荐

如何确保只有部分子类继承自父类

本文发布于:2023-11-05 19:12:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561626.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:子类

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!