Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我可以在构造函数中同时调用this和base重载吗?_C#_Constructor_Constructor Overloading - Fatal编程技术网

C# 我可以在构造函数中同时调用this和base重载吗?

C# 我可以在构造函数中同时调用this和base重载吗?,c#,constructor,constructor-overloading,C#,Constructor,Constructor Overloading,我能找到的最接近的线程是,但场景不同——要调用的基本构造函数是默认的。这里我需要指定要传递的参数 假设我们有以下场景: public class Base { public string Str; public Base(string s) { Str = s; } } public class A : Base { public string St

我能找到的最接近的线程是,但场景不同——要调用的基本构造函数是默认的。这里我需要指定要传递的参数

假设我们有以下场景:

    public class Base
    {
        public string Str;

        public Base(string s)
        {
            Str = s;
        }
    }

    public class A : Base
    {
        public string Str2;

        public A(string str2)
            : base(str2)
        {
            Str2 = str2;
        }

        public A(string str2, string str)
            : base(str)
        {
            Str2 = str2;
        }
    }
我希望避免在A的第二个构造函数重载中重复相同的逻辑(从技术上讲,我可以将所有逻辑封装到一个函数中,以减少复制粘贴/提高可维护性,因为最终所有重载都将依赖于相同的代码。如果没有其他解决方案,将遵循这一点)

我想我可以先调用A的第一个构造函数重载,然后调用基本构造函数重载。但似乎我不能


这里的方法是什么?

正确的方法是

public class A : Base
{
    public string Str2;

    public A(string str2)
        : this(str2, str2)
    {
    }

    public A(string str2, string str)
        : base(str)
    {
        Str2 = str2;
    }
}

A
的单参数构造函数调用
A
的双参数构造函数,使用
this(
而不是
base)向两个参数传递相同的字符串(
。然后删除单参数构造函数的主体,因为所有工作都在双参数构造函数中完成。

正确的方法是

public class A : Base
{
    public string Str2;

    public A(string str2)
        : this(str2, str2)
    {
    }

    public A(string str2, string str)
        : base(str)
    {
        Str2 = str2;
    }
}
A
的单参数构造函数调用
A
的双参数构造函数,使用
this(
而不是
base(
)向两个参数传递相同的字符串。然后删除单参数构造函数的主体,因为所有工作都在双参数构造函数中完成