简体   繁体   中英

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?

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 .

If test would be on A , then both A and B could access it. Or you could create an interface that's implemented by B and that A knows about and pass B as a parameter to 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.

But you could declare your method getState() as abstract:

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):

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. You define a contract on which class A can rely on. This way you can call getState() in class A and indirectly get the value of the field test from class B.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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