ICloneable 接口在 C# 中有什么用?


ICloneable 接口创建现有对象的副本,即克隆。

它只有一个方法 −

  • Clone() − clone() 方法创建了一个新对象,该对象是当前实例的副本。

下面是一个示例,展示如何使用 ICloneable 接口执行克隆 −

示例

 实时演示

using System;

class Car : ICloneable {
   int width;

   public Car(int width) {
      this.width = width;
   }

   public object Clone() {
      return new Car(this.width);
   }

   public override string ToString() {
      return string.Format("Width of car = {0}",this.width);
   }
}

class Program {
   static void Main() {
      Car carOne = new Car(1695);
      Car carTwo = carOne.Clone() as Car;

      Console.WriteLine("{0}mm", carOne);
      Console.WriteLine("{0}mm", carTwo);
   }
}

输出

Width of car = 1695mm
Width of car = 1695mm

更新日期:20-6 月-2020

2K+ 浏览次数

开启您的 职业生涯

通过完成课程获得认证

入门
广告
© . All rights reserved.