如何从c#中的构造函数中调用不同的构造函数?


How can I invoke a different constructor from a constructor in c#?

本问题已经有最佳答案,请猛点这里访问。

我有下面的课

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class ReportDataSource : IReportDataSource
{
    public string Name { get; set; }
    public string Alias { get; set; }
    public string Schema { get; set; }
    public string Server { get; set; }

    public ReportDataSource()
    {
    }

    public ReportDataSource(ReportObject obj)
    {
        this.Name = obj.Name;
        this.Alias = obj.Alias;
        this.Schema = obj.Schema;
        this.Server = obj.Server;
    }

    public ReportDataSource(ReportObject obj, string alias)
    {
        this.Name = obj.Name;
        this.Schema = obj.Schema;
        this.Server = obj.Server;

        this.Alias = alias;
    }

}

在构造函数中,ReportDataSource(ReportObject obj, string alias)的行为与ReportDataSource(ReportObject obj)的行为完全相同。唯一不同的是我可以覆盖alias属性。

有没有一种方法可以从ReportDataSource(ReportObject obj, string alias)内部调用ReportDataSource(ReportObject obj),这样我就不用复制代码了?

我试过这个

1
2
3
4
5
    public ReportDataSource(ReportObject obj, string alias)
        :base(obj)
    {
        this.Alias = alias;
    }

但我知道这个错误

'object' does not contain a constructor that takes 1 arguments

如何在C中调用不同的构造函数和in的构造函数?


this试试:

1
2
3
4
5
public ReportDataSource(ReportObject obj, string alias)
    :this(obj)
{
    this.Alias = alias;
}

它有时被称为构造函数链接。

An instance constructor initializer of the form this(argument-listopt) causes an instance constructor from the class itself to be invoked. The constructor is selected using argument-list and the overload resolution rules of §7.5.3.