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

问题描述

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



我尝试了什么:



将我的变量声明为私有

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

推荐答案

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


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

05-26 09:17