我可以从 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不包含任何访问修饰符时,假定为私有

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。因此,同一程序集中的任何人都可以看到它。类成员,因此字段、属性、方法或构造函数将默认为 private,这意味着只有该类才能访问它。

因此,如果两个类位于同一程序集中(不是 Namespace,则访问修饰符无关紧要(,则可以保留类声明,因此默认的内部访问修饰符很好。

您需要将构造函数更改为具有显式的内部或公共修饰符,以便可以访问它。请注意,如果您的类是内部的,您可以将方法等标记为公共,但它们仍然只能从该程序集内部访问,因为封装类是内部的。

最新更新