在 C# 中调用基本构造函数 [英] Calling the base constructor in C#
问题描述
如果我从基类继承并且想从继承类的构造函数传递一些东西给基类的构造函数,我该怎么做?
If I inherit from a base class and want to pass something from the constructor of the inherited class to the constructor of the base class, how do I do that?
例如,如果我从 Exception 类继承,我想做这样的事情:
For example, if I inherit from the Exception class I want to do something like this:
class MyExceptionClass : Exception
{
public MyExceptionClass(string message, string extraInfo)
{
//This is where it's all falling apart
base(message);
}
}
基本上我想要的是能够将字符串消息传递给基本的 Exception 类.
Basically what I want is to be able to pass the string message to the base Exception class.
推荐答案
将构造函数修改为以下内容,使其正确调用基类构造函数:
Modify your constructor to the following so that it calls the base class constructor properly:
public class MyExceptionClass : Exception
{
public MyExceptionClass(string message, string extrainfo) : base(message)
{
//other stuff here
}
}
请注意,构造函数不是您可以在方法中随时调用的东西.这就是您在构造函数体中的调用出错的原因.
Note that a constructor is not something that you can call anytime within a method. That's the reason you're getting errors in your call in the constructor body.
这篇关于在 C# 中调用基本构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!