![](/img/trans.png)
[英]C# in VS2005: in an inherited class, do you need to explicitly call the super-constructor?
[英]C# in VS2005: will this() execute the base constructor code for an inherited class?
對於VS2005中的C#,在繼承的類中調用this()
會導致執行基礎構造函數嗎?
編輯:我怎樣才能避免重寫x
和y
分配? 注意,我不希望MyObject(int num)構造函數執行base()構造函數。
public class MyObject : MyParentObject {
int x;
int y;
int z;
public MyObject() {
x = 5;
y = 10;
}
public MyObject(int num) : base(num) {
x = 5;
y = 10;
z = num;
}
base()
將由第一個構造函數隱式調用,以在派生類中運行:
public MyObject() {
x = 5;
y = 10;
}
public MyObject(int setZ) : this() {
z = setZ;
}
相當於:
public MyObject() : base() {
x = 5;
y = 10;
}
public MyObject(int setZ) : this() {
z = setZ;
}
除非您顯式調用參數化的基礎構造函數,否則將無提示地調用無參數基本構造函數。
如果你有
class Base { }
class Foo : Base { public Foo() { } }
這與說法沒有什么不同
class Foo : Base { public Foo() : base() { } }
因此,如果你有一個Foo的參數化構造函數,無論你用this()
做什么,都會調用base()
this()
除非你還有一個你明確調用的Base
的參數化構造函數。
class Base
{
public Base() { }
public Base(int bar) { }
}
class Foo : Base
{
public Foo() : base() { }
public Foo(int bar) : base(bar) { }
// also legal:
// public Foo() : base(1) { }
// public Foo(int bar) : base(1) { }
// public Foo(int bar) : base() { }
// public Foo(int bar) { } /* uses implicit call to base() */
// public Foo() { } /* ditto */
}
無論哪種方式,基類將首先通過無參數構造函數(隱式或顯式)或通過參數化構造函數(顯式)進行實例化。
我相信這是您正在尋找的語法:
class MainClass
{
MainClass()
{
//do something
}
}
class MyClass : MainClass
{
MyClass()
: base()
{
// do something else
}
}
調用base()將使它在當前構造函數之前運行基礎構造函數。
class BaseClass
{
BaseClass()
{
}
}
class MyClass : BaseClass
{
MyClass(int? id) : base()
{
}
MyClass() : this(null)
{
}
}
MyClass() : this(null)
將通過MyClass(int? id)
調用base MyClass(int? id)
或者你可以交換它並使MyClass(int? id) : this()
和MyClass() : base()
無論哪種方式,都將調用基礎構造函數。
如果沒有指定任何內容,則調用無參數的構造函數(如果有的話),否則將產生編譯器錯誤(如果您只有一個帶參數的基礎構造函數)
你試圖不在任何時候實例化你的基類? 那是不可能的; 無論是否重寫字段分配,您都必須顯式或隱式地調用基礎構造函數。
聽起來這不是你正在尋找的行為(因為它隱式地調用了base()
,但是你的代碼也是如此),但這可以節省你的重寫:
public class MyObject : MyParentObject {
int x;
int y;
int z;
public MyObject() {
x = 5;
y = 10;
}
public MyObject(int num) : this() {
z = num;
}
為什么要特別避免調用基類構造函數?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.