开发者

super statement in C#

I'm creating a class to manage exception in c#, and I'd like to create some constructor methods which recalls the superclass; this is the definition of my class:

class DataSourceNotFoundException: System.Exception 

but since in c# there is no super method what am I supposed to call to get开发者_StackOverflow社区 the constructor methods of System.Exception?


You call a parent constructor using base before the body of the constructor:

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

Obviously you don't have to just pass a parameter from your own constructor up as an argument to the base constructor:

public class FooException : Exception
{
    public FooException(int x) : base("Hello")
    {
        // Do something with x
    }
}

The equivalent to chain to a constructor in the current class is to use this instead of base.

Note that constructor chaining works very slightly differently in C# compared with Java, with respect to when instance variable initializers are run. See my article on C# constructors for more details.


In general the keyword base is what you want. Check http://msdn.microsoft.com/en-us/library/hfw7t1ce(v=vs.71).aspx


class DataSourceNotFoundException: System.Exception {
    public DataSourceNotFoundException()
        : base()
    {
        //some code
    }

    public DataSourceNotFoundException(string message, object other)
        : base(message)
    {
        //some code
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜