D
D
Dmitry Le2017-09-11 14:14:57
C++ / C#
Dmitry Le, 2017-09-11 14:14:57

Why, when calling an inherited method, does it not see the values ​​of the variables declared in the current class?

I'm trying to figure out inheritance in C#. Is it possible for methods declared in an abstract class to be somehow allowed to see the values ​​overridden during inheritance? And why, when passed to the getText(TestAbstarctClass item) function, is the value of item.sameTextValue taken from the abstract class, and not its subsequent implementation? If there is a sensible manual - give a link.

abstract class TestAbstarctClass
{
    public string sameTextValue = "Abstact text";

    public virtual string Name
    {
        get { return sameTextValue; }
        set { sameTextValue = value; }
    }

    public string testFF()
    {
        return sameTextValue;
    }

}

class Concrete1TestClass : TestAbstarctClass
{
    new public string sameTextValue = "Concrete1 text";

    public override string Name
    {
        get { return sameTextValue; }
        set { sameTextValue = value; }
    }
}


class Concrete2TestClass : TestAbstarctClass
{
    new public string sameTextValue = "Concrete2 text";
}

class Tester
{
    public void getText(TestAbstarctClass item)
    {
        Debug.Log(item.sameTextValue + " / " + item.Name + " / " + item.testFF());
    }
}

////////////////////////////
        Tester t = new Tester();
        t.getText(new Concrete1TestClass()); //Abstact text / Concrete1 text / Abstact text
        t.getText(new Concrete2TestClass()); //Abstact text / Abstact text / Abstact text

        Concrete2TestClass cl2 = new Concrete2TestClass();
        Debug.Log(cl2.sameTextValue + " / " + cl2.Name + " / " + cl2.testFF()); //Concrete2 text / Abstact text / Abstact text

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Arseniy Efremov, 2017-09-11
@FoMa_Le

Because the new keyword when declaring a class member hides the implementation of the base member. If you want to make a member accessible through a reference to the base class, declare it only in the base class. If you want to override the implementation of a virtual method , use the override keyword .
And in general, you should improve your understanding of OOP.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question