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

Ste*_*ett 1 c# constructor

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

例如:

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

    Company()
    {
        this.owner = new Person();
    }
}
Run Code Online (Sandbox Code Playgroud)

由于其保护级别,上面的返回"Person.Person()"无法访问.Person类看起来像这样:

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

    // DEFAULT CONSTRUCTOR
    Person() 
    {
        this.name = "";
        this.surname = "";
    }
}
Run Code Online (Sandbox Code Playgroud)

这里有什么我想念的吗?不应该从同一名称空间的任何地方访问构造函数吗?

ViR*_*iTy 10

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

编译器甚至会给你一个提示:

error CS0122: 'Person.Person()' is inaccessible due to its protection level
Run Code Online (Sandbox Code Playgroud)

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

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

class_member_declaration指定为

class_member_declaration
    : ...
    | constructor_declaration
    | ...
    ;
Run Code Online (Sandbox Code Playgroud)

只有默认构造函数类时默认都是公有的没有定义为抽象的.

因此改变

Person() { }
Run Code Online (Sandbox Code Playgroud)

public Person() { }
Run Code Online (Sandbox Code Playgroud)

  • @Stett [Namespaces](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/namespaces/)与[访问修饰符]没有任何关系**(https:// docs .microsoft.com/EN-US/DOTNET/CSHARP /语言参考/关键字/访问修饰符).它们用于*非常不同的目的. (6认同)