C#中的超级语句 [英] super statement in C#
问题描述
我正在创建一个类来管理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
但是由于在c#中没有超级方法,我应该调用什么来获取 System.Exception
的构造方法?
but since in c# there is no super method what am I supposed to call to get the constructor methods of System.Exception
?
推荐答案
在构造器主体之前,使用 base
调用父构造器:
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
}
}
等效于链接到当前类中的构造函数的方法是使用 this
而不是 base
.
The equivalent to chain to a constructor in the current class is to use this
instead of base
.
请注意,相对于何时运行实例变量初始化程序,构造函数链在C#中与Java的工作原理非常不同.有关更多详细信息,请参见我的有关C#构造函数的文章.
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.
这篇关于C#中的超级语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!