在派生类中访问的基类变量 [英] access base class variable in derived class

查看:103
本文介绍了在派生类中访问的基类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;
    }
}



我要访问子类INTF和整型什么我输入..但我总是得到这两个变量的值0 0是两个变量的缺省值。

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的进阶..

推荐答案

是的,零是你应该得到的东西,因为你让子类的实例,并没有任何值分配给它的继承变量,

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.

这篇关于在派生类中访问的基类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆