简体   繁体   English

如何从派生类C#访问基类值

[英]How to access a base class value from derived class c#

Can any one let me know "How to access base class variables in derived class"? 谁能让我知道“如何在派生类中访问基类变量”?

Example: 例:

Class 1.cs Code 1.cs类代码

public class baseClass
{
    public int intF = 0, intS = 0;
    public int addNo()
    {
        int intReturn = 0;
        intReturn = intF + intS;
        return intReturn;
    }
}

Public class child : baseClass
{
    public int add()
    {
        int intReturn = 0;
        intReturn = base.intF * base.intS;
        return intReturn;
    }
}

Class2.cs Code Class2.cs代码

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

The problem is in child class which gets inherited from base class.. 问题出在从基类继承的子类中。

The value of intF and intS is always showing as 0 instead of 5&4. intF和intS的值始终显示为0,而不是5&4。

Can any one let me know where I am going wrong? 谁能让我知道我要去哪里错了?

Regards, 问候,

GVNSandeep GVNSandeep

Instance fields intF and intS belong to... instance, not to a type. 实例字段intFintS属于...实例,而不属于类型。 When you're setting them for obj instance, the same fields in obj1 instance have their default values (zeroes). obj实例设置它们时, obj1实例中的相同字段具有其默认值(零)。

You must assign 5 and 4 this way: 您必须以这种方式分配5和4:

child obj1 = new child();
obj1.intF = 5;
obj1.intS = 4;

Your fields are not static . 您的字段不是static There is one separate field for each instance (object) you create. 您创建的每个实例(对象)都有一个单独的字段。

obj and obj1 are distinct instances. objobj1是不同的实例。

By the way, there's no need to use the base keyword in this situation. 顺便说一句,在这种情况下不需要使用base关键字。 The two fields are in the child class because of inheritance. 这两个字段child类,因为继承。 Only use base when the current class overrides or hides a member from the base class. 仅使用base时当前类覆盖或隐藏从基类的部件。

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

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