Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从超类获取字段_C#_Inheritance - Fatal编程技术网

C# 从超类获取字段

C# 从超类获取字段,c#,inheritance,C#,Inheritance,我有以下抽象类: abstract class Customer { private string address { get; set; } private int phone { get; set; } public Customer(string address, int phone) { this.address = address; this.phone = phone; } } 然后我有以下从custome

我有以下抽象类:

 abstract class Customer
{
    private string address { get; set; }
    private int phone { get; set; }

    public Customer(string address, int phone)
    {
        this.address = address;
        this.phone = phone;
    }
}
然后我有以下从customer类继承的类:

   class Private : Customer
{

    private string name { get; set; }
    private int age { get; set; }
    private string sex { get; set; }

    public Private(string name, int age, string sex, string address, int phone) : base(address, phone)
    {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

我的问题是:如何访问私有类上的phone和address字段?

对于继承类可以访问的所有内容,请使用
protected
修饰符,而不是
Private

从文档中:

受保护的成员可以在其类内以及由派生类实例访问


把它们公之于众。哦,天哪,我觉得自己太蠢了。感谢您的快速回复…您可以从构造函数访问它们。如果要从方法访问它们,它们需要是公共的或受保护的。@Quantic从构造函数访问它是什么意思?就在
this.sex=sex
下面,您可以键入,
address=“test”
this.name=address
,即,您可以访问其
get
set
访问器,即使它是私有的,但只能从派生类构造函数访问。如果你想从一个方法中做同样的事情,那么它必须被保护或公开。我应该明确地说,我只是测试了这个,它工作了,目前我找不到一个MSDN页面,明确说明为什么你可以这样做。可能派生构造函数的作用域实际上在基构造函数内。谢谢。我觉得我应该自己想到这一点。