在C#中调用基本构造函数

若是我从基类继承,并但愿将某些东西从继承类的构造函数传递给基类的构造函数,该怎么作? 函数

例如, this

若是我从Exception类继承,我想作这样的事情: spa

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

基本上,我想要的是可以将字符串消息传递给基本Exception类。 code


#1楼

将您的构造函数修改成如下代码,以便它正确调用基类的构造函数: 对象

public class MyExceptionClass : Exception
{
    public MyExceptionClass(string message, string extrainfo) : base(message)
    {
        //other stuff here
    }
}

注意,构造函数不是您能够在方法中随时调用的。 这就是在构造函数主体中调用时出错的缘由。 继承


#2楼

若是因为新的(派生的)类须要进行一些数据操做而须要当即调用基本构造函数,那么最好的解决方案是采用工厂方法。 您须要作的是将派生的构造函数标记为私有,而后在您的类中建立一个静态方法来处理全部必要的工做,而后调用该构造函数并返回该对象。 字符串

public class MyClass : BaseClass
{
    private MyClass(string someString) : base(someString)
    {
        //your code goes in here
    }

    public static MyClass FactoryMethod(string someString)
    {
        //whatever you want to do with your string before passing it in
        return new MyClass(someString);
    }
}

#3楼

public class MyExceptionClass : Exception
{
    public MyExceptionClass(string message,
      Exception innerException): base(message, innerException)
    {
        //other stuff here
    }
}

您能够将内部异常传递给构造函数之一。 string


#4楼

确实能够使用base (某些东西)来调用基类的构造函数,可是若是重载,请使用this关键字 it

public ClassName() : this(par1,par2)
{
// do not call the constructor it is called in the this.
// the base key- word is used to call a inherited constructor   
} 

// Hint used overload as often as needed do not write the same code 2 or more times

#5楼

请注意,能够在对基本构造函数的调用中使用静态方法。 io

class MyExceptionClass : Exception
{
     public MyExceptionClass(string message, string extraInfo) : 
         base(ModifyMessage(message, extraInfo))
     {
     }

     private static string ModifyMessage(string message, string extraInfo)
     {
         Trace.WriteLine("message was " + message);
         return message.ToLowerInvariant() + Environment.NewLine + extraInfo;
     }
}
相关文章
相关标签/搜索