1.4.3. 实现继承

it2024-07-18  86

实现类的继承,首先声明一个基类 public class Shape { } 在声明一个子类 public class Size { } 实现继承 public class Size:Shape { } 新建两个接口 public interface IChangShape { } public interface IChangeSize { } 实现接口 public class Size:Shape,IChangShape,IChangeSize { }

注意:

如果一个类要同时继承接口和类,那么必须把继承的类放在最前面,然后将接口放在后面

结构实现接口 public struct SizeStruct:IChangeSize,IChangShape { } 举个继承的例子 首先新建一个形状的基类class Shape,基类中有两个属性,一个大小,一个位置。然后定义一个长方形形和正方形,然后继承这个基类。 using System; namespace test { class Program { static void Main(string[] args) { Rectangle rectangle = new Rectangle { Position = new Position { X = 1000, Y = 2000 }, Size = new Size { Height = 10, Width = 20} }; Square square = new Square { Position = new Position { X = 2000, Y = 2000 }, Size = new Size { Height = 10, Width = 10 } }; } public class Position { public int X { get; set; } public int Y { get; set; } } public class Size { public int Width { get; set; } public int Height { get; set; } } public class Shape { public Position Position { get; set; } = new Position(); public Size Size { get; set; } = new Size(); } public class Rectangle : Shape { } public class Square:Shape { } } }

当实例化圆形和正方形时就会发现可以调用基类的大小和位置。

最新回复(0)