我可以在构造函数中同时调用this和base重载吗? [英] Can I call both this and base overloads in a constructor?
问题描述
我能找到的最接近的线程是这一个,但是情况有所不同-要调用的基本构造函数是默认构造函数.在这里,我需要指定要传递的参数.
The closest thread I could find was this one, but the scenario there is different - the base constructor to be called is the default one. Here I need to specify which parameter I want to pass it.
假设我们有以下情形:
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的第二个构造函数重载中重复相同的逻辑(从技术上讲,我可以将所有逻辑包装到一个减少复制粘贴/提高可维护性的函数中,因为最终所有重载都依赖于同一代码.如果没有其他解决方案,请按照此步骤操作.)
I want to avoid repeating the same logic in A's 2nd constructor overload (technically I could wrap all the logic into a function reducing the copy-paste / improving maintainability, for at the end all overloads would rely in the same code. Would follow this if there is no other solution).
我以为我可以先调用A的第一个构造函数重载,然后再调用基数.但似乎我做不到.
I thought I could call first A's 1st constructor overload and afterwards the base one. But seems I can't.
这里的方法是什么?
推荐答案
正确的方法是
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
的2参数构造函数,使用 this(
而不是 base(
.然后删除单参数构造函数的主体,因为所有工作都在两个参数构造函数中完成.
The single parameter constructor of A
calls the 2 parameter constructor of A
passing in the same string to both parameters using this(
instead of base(
. You then remove the body of the single parameter constructor because all of the work is being done in the two parameter constructor.
这篇关于我可以在构造函数中同时调用this和base重载吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!