在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
(1)protected The protected keyword is a member access modifier. A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member. //proteted修饰的方法 (本类 和 派生类 内部可访问) class A { protected int x = 123; } class B : A { void F() { A a = new A(); B b = new B(); a.x = 10; // Error b.x = 10; // OK } } (2)base The base keyword is used to access members of the base class from within a derived class:
(用于访问基类的成员,仅限于在派生类内部. base.方法名()) A base class access is permitted only in a constructor, an instance method, or an instance property accessor. (只可在派生类(derived class)的 构造函数,实例方法,实例属性 中用base访问基类) // keywords_base.cs // Accessing base class members using System; public class Person { protected string ssn = "444-55-6666"; protected string name = "John L. Malgraine"; public virtual void GetInfo() { Console.WriteLine("Name: {0}", name); Console.WriteLine("SSN: {0}", ssn); } } class Employee: Person { public string id = "ABC567EFG"; public override void GetInfo() { // Calling the base class GetInfo method: base.GetInfo(); Console.WriteLine("Employee ID: {0}", id); } } class TestClass { public static void Main() { Employee E = new Employee(); E.GetInfo(); } } 结果: Name:John L. Malgraine SSN:444-55-6666 Employee ID:ABC567EFG (3) virtual -overrid (必配套使用) 基类中用virtual修饰的方法,在派生类中可用override重写 class TestClass { public class Shape { public const double PI = Math.PI; protected double x, y; public Shape() { } public Shape(double x, double y) { this.x = x; this.y = y; } public virtual double Area() { return x * y; } } public class Circle : Shape { public Circle(double r) : base(r, 0) { } public override double Area() { return PI * x * x; } } class Sphere : Shape { public Sphere(double r) : base(r, 0) { } public override double Area() { return 4 * PI * x * x; } } class Cylinder : Shape { public Cylinder(double r, double h) : base(r, h) { } public override double Area() { return 2 * PI * x * x + 2 * PI * x * y; } } static void Main() { double r = 3.0, h = 5.0; Shape c = new Circle(r); Shape s = new Sphere(r); Shape l = new Cylinder(r, h); // Display results: Console.WriteLine("Area of Circle = {0:F2}", c.Area()); Console.WriteLine("Area of Sphere = {0:F2}", s.Area()); Console.WriteLine("Area of Cylinder = {0:F2}", l.Area()); } } /* Output: Area of Circle = 28.27 Area of Sphere = 113.10 Area of Cylinder = 150.80 */
|
请发表评论