2013-02-11 86 views
3

我一直在试图写我自己的自定义构造函数,但得到有关base()构造函数的错误。我也一直在寻找如何解决这个错误,但没有发现任何东西,网络上的所有例子都显示了和我的几乎相同的代码。自定义异常和基构造器

全Exception.cs内容:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 

namespace RegisService 
{ 
public class Exceptions : Exception 
{   
} 

    public class ProccessIsNotStarted : Exceptions 
    { 
     ProccessIsNotStarted() 
      : base() 
     { 
      //var message = "Formavimo procesas nestartuotas"; 
      //base(message); 
     } 

     ProccessIsNotStarted(string message) 
      : base(message) {} 

     ProccessIsNotStarted(string message, Exception e) 
      : base(message, e) {} 
    } 
} 

base()第一超负荷工作,没有错误被抛出。第二和第三 重载告诉我,:

"RegisService.Exceptions does not contain a constructor that takes 1(2) arguments"

我一直在试图解决这个错误还有一个办法:

ProccessIsNotStarted(string message)    
    { 
     base(message); 
    } 

    ProccessIsNotStarted(string message, Exception e) 
    { 
     base(message, e); 
    } 

这个时候,VS是告诉我,:

"Use of keyword 'base' is not valid in this context"

那么,问题在哪里?看起来像base()构造函数有一些奇怪的重载,或者我用不恰当的方式调用它?

回答

6

您的Exceptions类需要定义您想要提供的所有构造函数。 System.Exception的构造函数不是虚拟的或抽象的。关键字base不会调用所有基类的成员,而是调用您在类声明中提供的一个基类。看看这个:

public class Exceptions : Exception 
{ 
    public Exceptions(string message) 
     : base(message) {} 
} 

public class ProccessIsNotStarted : Exceptions 
{ 
    public ProccessIsNotStarted() 
     : base() 
    { 
    } 

    public ProccessIsNotStarted(string message) 
     : base(message) 
    { 
     // This will work, because Exceptions defines a constructor accepting a string. 
    } 

    public ProccessIsNotStarted(string message, Exception e) 
     : base(message, e) 
    { 
     // This will not work, because Exceptions does not define a constructor with (string, Exception). 
    } 
} 

默认情况下,无参数构造函数被定义。要隐藏它,你需要声明它private

关于向MSDN你应该让你的异常的继承层次平:

If you are designing an application that needs to create its own exceptions, you are advised to derive custom exceptions from the Exception class. It was originally thought that custom exceptions should derive from the ApplicationException class; however in practice this has not been found to add significant value.

您还可以看看this page

+0

谢谢,它有帮助。我只需为每个'Exceptions'超载添加'public'。 – Masius 2013-02-11 12:06:14

1

base指的是直接基类,而不是链中的任何基类。您的ProcessIsNotStarted类是RegisService.Exceptions的直接子类型,而不是System.Exception。 RegisService.Exceptions没有带签名(字符串,异常)或(字符串)的构造函数。

尝试将两个构造函数添加到您的RegisService.Exceptions基类中。

1

如果您检查下面的一段代码:

public class Exceptions : Exception 
{   
} 

你会发现有没有构造。那么,这是一种谎言,因为可以使用默认的公共构造函数,但是没有自定义的构造函数。

如果你想通过Exceptions暴露的Exception的构造函数,然后你将不得不定义它们Exceptions和使用base从那里打电话给他们,因为继承异常调用base呼吁Exceptions,因此Exception不是他们base,因此构造函数无法访问。你可以做new Exceptions("", null)很好。而且,你的基构造函数在使用继承时调用。

不管你是否从这个继承链中获得任何价值,我都不知道,你可能想要拿出中间人,可以这么说,按照另一个建议。