如何确保只有部分子类继承自父类 [英] How do I ensure that only some of my child classes inherit from the parent class

查看:131
本文介绍了如何确保只有部分子类继承自父类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只希望来自主/父类的数据相应地由子类继承



我尝试了什么:



将我的变量声明为私有

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...


这篇关于如何确保只有部分子类继承自父类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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