简体   繁体   English

C#从抽象类访问基类变量/函数

[英]C# Access base class variables/functions from abstract class

Maybe its not possible or i am mixing something up, but its breaking my head.也许这是不可能的,或者我正在混淆一些东西,但它打破了我的头。

Let's say, we got an abstract class A and a class B based of A. Is it possible for A to access variables/functions from B?假设我们有一个抽象类 A 和一个基于 A 的类 B。 A 是否可以从 B 访问变量/函数?

Example:例子:

 abstract class A
 {
    public bool activeA = false;

    public bool getState()
    {
        return test; // The variable from class B
    }
 }

 class B : A
 {
    public bool test = true;

    public void isActive()
    {
         return base.getState(); // So this should return true because getState() should access the variable test^^
    }

 }

No, this is not possible.不,这是不可能的。 A doesn't know anything about B or potentially C..Z . AB或潜在的C..Z

If test would be on A , then both A and B could access it.如果testA ,那么AB都可以访问它。 Or you could create an interface that's implemented by B and that A knows about and pass B as a parameter to A .或者您可以创建一个由B实现的接口,并且A知道并将B作为参数传递给A

This could look like this:这可能是这样的:

interface IB
{
    bool Test { get; }
}

abstract class A
{
   public bool activeA = false;

   public bool getState(IB arg)
   {
       return arg.Test;
   }
}

class B : A, IB
{
   public bool Test => true;

   public bool isActive()
   {
         return base.getState(this); 
    }
 }

No, that's not possible.不,那不可能。 The abstract class knows nothing about the classes which inherit from it, so it can't use their properties.抽象类对从它继承的类一无所知,因此它不能使用它们的属性。

这是不可能的,因为 A 类不知道 B 存在。

As already mentioned: it is not generally possible to access the field test of class B from class A.正如已经提到的:通常不可能从 A 类访问 B 类的现场测试。

But you could declare your method getState() as abstract:但是你可以将你的方法 getState() 声明为抽象的:

abstract class A
{
    public abstract bool getState();

    void AccessState()
    {
        Console.WriteLine("state: {0}", getState());
    }
}

All classes derving from A must implement the method getState (or be abstract themselves):从 A 派生的所有类都必须实现 getState 方法(或者本身是抽象的):

class B : A
{
    bool test = true;
    public override bool getState()
    {
        return test;
    }
}

This way you enforce all non abstract inheritors of class A to provide an implementation of all abstract methods and properties.通过这种方式,您可以强制类 A 的所有非抽象继承者提供所有抽象方法和属性的实现。 You define a contract on which class A can rely on.您定义了一个 A 类可以依赖的契约。 This way you can call getState() in class A and indirectly get the value of the field test from class B.这样就可以在A类中调用getState(),间接从B类中获取现场测试的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM