Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

c# - 在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?

(如果我从基类继承,并希望将某些东西从继承类的构造函数传递给基类的构造函数,该怎么做?)

For example,

(例如,)

If I inherit from the Exception class I want to do something like this:

(如果我从Exception类继承,我想做这样的事情:)

class MyExceptionClass : Exception
{
     public MyExceptionClass(string message, string extraInfo)
     {
         //This is where it's all falling apart
         base(message);
     }
}

Basically what I want is to be able to pass the string message to the base Exception class.

(基本上,我想要的是能够将字符串消息传递给基本Exception类。)

  ask by lomaxx translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

(这就是在构造函数主体中调用时出错的原因。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...