为什么 C# 不允许默认使用父级的构造函数?
Why doesn't C# allow using parent's constructor by default?
请注意,我不会问如何做某事。这个问题是关于语言作者的设计决策。
假设您有一个带有构造函数和方法的基础 class:
public class BaseClass
{
public BaseClass(string argument)
{
}
public void SomeMethod()
{
}
}
并且您还导出了 class,它是空的(或者,实际上,还有其他不相关的东西):
public class DerivedClass : BaseClass
{
public DerivedClass() // Some other constructor not used in the example, just so it will compile
}
因此,当您尝试在派生 class 的实例上调用该方法时,它会起作用,但如果您尝试调用构造函数,则会导致编译错误:
var d = new DerivedClass("argument"); // error CS1729: The type `DerivedClass' does not contain a constructor that takes `1' arguments
d.SomeMethod(); // Works OK
这个语言设计决定背后的原因是什么?
这是因为构造函数不是继承的。
有关详细信息,请参阅此 post 以了解为什么会这样:Why are constructors not inherited?
请注意,我不会问如何做某事。这个问题是关于语言作者的设计决策。
假设您有一个带有构造函数和方法的基础 class:
public class BaseClass
{
public BaseClass(string argument)
{
}
public void SomeMethod()
{
}
}
并且您还导出了 class,它是空的(或者,实际上,还有其他不相关的东西):
public class DerivedClass : BaseClass
{
public DerivedClass() // Some other constructor not used in the example, just so it will compile
}
因此,当您尝试在派生 class 的实例上调用该方法时,它会起作用,但如果您尝试调用构造函数,则会导致编译错误:
var d = new DerivedClass("argument"); // error CS1729: The type `DerivedClass' does not contain a constructor that takes `1' arguments
d.SomeMethod(); // Works OK
这个语言设计决定背后的原因是什么?
这是因为构造函数不是继承的。
有关详细信息,请参阅此 post 以了解为什么会这样:Why are constructors not inherited?