无法访问受保护的变量

时间:2017-07-08 18:05:59

标签: c# inheritance

我创建了一个简单的测试项目,将一个类用作自定义List类型,并且在声明变量时有一些关于使用不同语法的问题。

我有一个名为CustomerInfo的类,它定义了为客户信息存储所需的所有变量,这些变量将被添加到列表中,如下所示:

    protected string Firstname { get; set; }

    protected string Surname { get; set; }

    protected int Age
    {
        get
        {
            return Age;
        }
        set
        {
            if(value < 0)
            {
                throw new AgeException("Age cannot be a value below 0");
            }
            else
            {
                Age = value;
            }
        }
    }

    protected string Gender { get; set; }

问题:
1)为什么下面的代码不允许我访问CustomerInfo类中的受保护变量,即使我继承了这个类?

class Program : CustomerInfo
{
    static void Main(string[] args)
    {
        CustomerInfo custInfo = new CustomerInfo();
        custInfo.Firstname = "Richard"; //not working
        custInfo.Surname = "Smith"; //not working

        List<CustomerInfo> custList = new List<CustomerInfo>();
        custList.Add(custInfo);
    }
}

2)在查看Windows窗体应用程序时,它们已经在您创建的任何窗体的代码中包含Form的继承。如果你必须继承一个类来访问受保护的变量&amp;它拥有的方法,如果每个表单都有一个你无法删除的继承,你如何访问变量?

由于

2 个答案:

答案 0 :(得分:2)

  

protected关键字是成员访问修饰符。受保护的成员   可以在其类和派生类实例中访问。   来源MSDN

CustomerInfo custInfo = new CustomerInfo();
custInfo.Firstname = "Richard"; //not working
custInfo.Surname = "Smith"; //not working

此代码无效,因为Firtsname类无法访问您的custInfo SurnameProgram。但是您应该能够执行以下操作,因为Program类继承自CustomerInfo

Firstname = "Richard";
Surname = "Smith";

对于第二个问题,您可以执行以下操作:

Class1 : Form
{
     // here will be your protected members
}
Class2 : Class1

答案 1 :(得分:2)

你误解了继承的目的。继承旨在表示两个对象之间的关系,其中一个是另一个对象的更专用版本。这有时被称为&#34; is-a&#34;关系。

考虑以下类定义:

class Fruit {}
class Apple : Fruit {}
class Banana: Fruit {}

在这种情况下,AppleBanana都从Fruit继承,以表达&#34; is-a&#34;关系 - Banana Fruit。在面向对象的设计中,这允许您编写如下方法:

class Person
{
    public void Eat(Fruit fruit) {}
    {
        // stuff goes here
    }
}

Eat方法允许Person类吃掉Fruit的所有内容,包括派生自Fruit的类。所以你可以做到以下几点:

Person person = new Person();
Apple apple = new Apple();
Banana banana = new Banana();

person.Eat(apple);
person.Eat(banana);

将此与您编写的类定义进行比较:

class Program : CustomerInfo

在OOP语言中,这表示&#34; Program CustomerInfo。&#34;我不认为这就是你想要的。使用protected关键字在这里没有意义,因为您的继承关系没有意义。如果Program应该能够访问CustomerInfo成员,则应将其声明为publicinternal