【问题标题】:How can I invoke a different constructor from a constructor in c#? [duplicate]如何在 c# 中调用与构造函数不同的构造函数? [复制]
【发布时间】:2016-12-09 20:51:43
【问题描述】:

我有以下课程

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),这样我就不必复制我的代码了?

我试过了

    public ReportDataSource(ReportObject obj, string alias)
        :base(obj)
    {
        this.Alias = alias;
    }

但我收到此错误

'object' 不包含带 1 个参数的构造函数

如何在 c# 的构造函数中调用与 with 不同的构造函数?

【问题讨论】:

    标签: c#


    【解决方案1】:

    试试this:

    public ReportDataSource(ReportObject obj, string alias)
        :this(obj)
    {
        this.Alias = alias;
    }
    

    它有时被称为构造函数链

    this(argument-listopt) 形式的实例构造函数初始化器strong> 导致调用类本身的实例构造函数。使用 argument-list 和第 7.5.3 节的重载解析规则选择构造函数。

    【讨论】:

    • 成功了!谢谢。时间允许,我会接受你的回答
    猜你喜欢
    • 2018-10-17
    • 1970-01-01
    • 2016-03-25
    • 2022-11-21
    • 2013-04-17
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    相关资源
    最近更新 更多