投入:基地功能?

时间:2010-04-06 14:48:06

标签: c# .net

 public LocalizedDisplayNameAttribute(string displayNameKey)
            : base(displayNameKey)
        {

        }

如果我把:base放在课堂上的功能之后是什么意思?

3 个答案:

答案 0 :(得分:3)

base表示您正在从此类的构造函数中调用基类的构造函数。

它仅对构造函数有效,而不是常规方法。在您的情况下,当创建LocalizedDisplayNameAttribute时,它会将displayNameKey参数传递给其基类的构造函数。

答案 1 :(得分:3)

这意味着您将调用类的基类的相应构造函数。

考虑一下:

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"

如果这仍然没有任何意义,你可能应该阅读更多关于面向对象语言中的构造函数,例如here

答案 2 :(得分:0)

你所拥有的是Constructor而不是函数或方法(构造函数是在实例化类时自动调用的特殊方法)。在构造函数之后添加:base(参数)允许您使用传递给类构造函数的参数来调用基类的构造函数(您的类继承自的类)。

可以在http://www.yoda.arachsys.com/csharp/constructors.html找到关于构造函数的好教程,这有助于清除它。