繁体   English   中英

我可以从C#中另一个类的构造函数调用构造函数吗?

[英]Can I call a constructor from the constructor of another class in C#?

我是C#的新手,想知道在同一个名称空间中有两个类时,是否可以在另一个的构造函数中调用一个的构造函数?

例如:

class Company
{
    // COMPANY DETAILS
    Person owner;
    string name, website;

    Company()
    {
        this.owner = new Person();
    }
}

上面的返回“ Person.Person()”由于其保护级别而无法访问。 人员类如下所示:

class Person
{
    // PERSONAL INFO
    private string name, surname;

    // DEFAULT CONSTRUCTOR
    Person() 
    {
        this.name = "";
        this.surname = "";
    }
}

我在这里想念什么吗? 是否应该可以从同一命名空间中的任何位置访问构造函数?

您将构造函数定义为私有,因此无法访问它。

编译器甚至给您一个提示

error CS0122: 'Person.Person()' is inaccessible due to its protection level

访问修饰符C#6.0规范状态:

class_member_declaration不包含任何访问修饰符时,将假定为private

class_member_declaration被指定为

class_member_declaration
    : ...
    | constructor_declaration
    | ...
    ;

只有默认的构造函数当类没有被定义为抽象的默认都是公有的。

因此改变

Person() { }

public Person() { }

在C#中,我们具有访问修饰符。 当前的选项是

Public - everyone has access
Internal - can only access from same assemnly
Protected - only the class and classes derived from the class can access members marked as protected
Protected Internal - accessible from any class in the same assembly or from any class derived from this class in any assembly
Private protected - only accessible from a class that is derived from this class AND in the same assembly 
Private - only accessible in the declaring class

有一个新的来临,但让我们省略。

对于您的问题而言,重要的是代码中应包含哪些内容。 未指定访问修饰符的类将默认为internal。 这样,在同一程序集中的任何人都可以看到它。 类成员,因此字段,属性,方法或构造函数将默认为私有,这意味着只有该类有权访问它。

因此,对于您来说,如果两个类都在同一程序集中(而不是对访问修饰符无关的命名空间),则可以保留类声明,这样默认的内部访问修饰符就可以了。

您需要将自己的构造方法更改为具有显式的内部或公共修饰符,以便您可以对其进行访问。 请注意,如果您的类是内部类,则可以将方法等标记为公共类,但由于encapsulatong类是内部类,它们仍然只能从该程序集中进行访问。

暂无
暂无

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

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