[英]Putting :base after function?
public LocalizedDisplayNameAttribute(string displayNameKey)
: base(displayNameKey)
{
}
if i put :base
after the function in the class what does that mean? 如果我在类中的函数之后放
:base
,那是什么意思?
base
indicates that you're calling the base class' constructor from this class' constructor. base
表示您正在从此类的构造函数中调用基类的构造函数。
It is only valid for constructors, not regular methods. 它仅对构造函数有效,对常规方法无效。 In your case, when a
LocalizedDisplayNameAttribute
is created, it passes the displayNameKey
parameter to its base class' constructor. 在您的情况下,创建
LocalizedDisplayNameAttribute
时,它将displayNameKey
参数传递给其基类的构造函数。
It means that you will invoke the according constructor of the base class of your class. 这意味着您将调用类的基类的相应构造函数。
Consider this: 考虑一下:
public class A {
public A() {
Console.WriteLine("You called the first constructor");
}
public A(int x) {
Console.WriteLine("You called the second constructor with " + x);
}
}
public class B : A {
public B() : base() { } // Calls the A() constructor
}
public class C : A {
public C() : base(10) { } // Calls the A(int x) constructor
}
public class D : A {
public D() { } // No explicit base call; Will call the A() constructor
}
...
new B(); // Will print "You called the first constructor"
new C(); // Will print "You called the second constructor with 10"
new D(); // Will print "You called the first constructor"
If this still doesn't make any sense, you should probably read a bit more about constructors in object oriented languages, for example here . 如果这仍然没有任何意义,您可能应该阅读更多有关面向对象语言的构造函数的信息,例如here 。
What you have there is a Constructor and not a function or method (a constructor is a special method that is called automatically when your class is instantiated). 您拥有的是构造函数,而不是函数或方法(构造函数是一种特殊的方法,在实例化您的类时会自动调用它)。 Adding
:base
(parameter) after the constructor allows you to call the constructor of the base class (the class your class inherited from) with the parameter passed into your class constructor. 在构造函数之后添加
:base
(参数),使您可以使用传递给类构造函数的参数来调用基类(继承自您的类的类)的构造函数。
A good tutorial on constructors can be found at http://www.yoda.arachsys.com/csharp/constructors.html which should help clear this up. 可以在http://www.yoda.arachsys.com/csharp/constructors.html上找到有关构造函数的良好教程,这应该有助于清除此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.