access base class variable in derived class

房东的猫 提交于 2019-12-10 07:51:50

问题


class Program
{
    static void Main(string[] args)
    {
        baseClass obj = new baseClass();
        obj.intF = 5;
        obj.intS = 4;
        child obj1 = new child();
        Console.WriteLine(Convert.ToString(obj.addNo()));
        Console.WriteLine(Convert.ToString(obj1.add()));
        Console.ReadLine();
    }
}
public class baseClass
{
    public int intF = 0, intS = 0;
    public int addNo()
    {
        int intReturn = 0;
        intReturn = intF + intS;
        return intReturn;
    }
}
class child : baseClass
{
    public int add()
    {
        int intReturn = 0;
        intReturn = base.intF * base.intS;
        return intReturn;
    }
}

I want to access intF and intS in child class whatever i input.. but i always get the values of both variables 0. 0 is default value of both variables.

Can anyone tell me that how can i get the value???

thx in adv..


回答1:


Yes, Zero is what you should get, since you made single instance of child class and did not assign any value to its inherited variables,

child obj1 = new child();

rather you have instantiated another instance of base class separately and assign value to its members,

baseClass obj = new baseClass();

both runtime both the base class instance and child instance are totally different objects, so you should assign the child values separately like

obj1.intF = 5;
obj1.intS = 4;

then only you shall get the desired result.




回答2:


You've got two separate objects - that's the problem. The values of the base class variables in the object referred to by obj1 are 0, because they haven't been set to anything else. There's nothing to tie that object to the object referred to by obj.

If you need to access the variables of another object, you'd have to make that object available to the one trying to access the data. You could pass obj as an argument to a method, or perhaps make it a property. There are lots of different approaches here, but we don't know what the bigger picture is - what you're really trying to do. Once you understand why it's not working as you expect it to, you can start thinking about what you're really trying to do.

Just to be clear, this has nothing to do with inheritance. It has everything to do with you creating two distinct objects. You'd get the same effect if you just used a single class, but created two different instances of that class.



来源:https://stackoverflow.com/questions/5296026/access-base-class-variable-in-derived-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!