用单一方法克隆派生类型

时间:2017-07-18 06:51:06

标签: c# oop

我有一个非抽象基类Vehicle,它有三种派生类型。

  • Car
  • Motorcycle
  • Tractor

我正在查看名为VehicleBuilder的服务 哪个方法CloneVehicle采用Vehicle类型的参数并返回所有三种派生类型的克隆对象。

这是我的CloneVehicle

public Vehicle CloneVehicle (Vehicle v)
{
   var newVehicle = ClonebaseVehicle(v); // Clones all the types in the Base class
   if(Vehicle.Type == Vehicles.Tractor)
    {
        // Clone individual fields
        var tractor = new Tractor();
        tractor = newVehicle as Tractor;
        tractor.TractorCapacity  = 50 ; // tractor is coming null here
        return tractor; 
    }
}

我想重用ClonebaseVehicle并且无法创建构造函数,因为类来自不同的DLL。 我可以使用基类引用克隆已解除对象的任何其他方法吗?

我无法更改Vehicle类或其任何派生类以在其中创建抽象方法

1 个答案:

答案 0 :(得分:3)

... "dependencies": { "@angular/animations": "^4.0.0", "@angular/common": "^4.0.0", "@angular/compiler": "^4.0.0", "@angular/core": "^4.0.0", "@angular/forms": "^4.0.0", "@angular/http": "^4.0.0", "@angular/platform-browser": "^4.0.0", "@angular/platform-browser-dynamic": "^4.0.0", "@angular/router": "^4.0.0", "core-js": "^2.4.1", "rxjs": "^5.1.0", "zone.js": "0.8.12" }, "devDependencies": { "@angular/cli": "1.2.1", "@angular/compiler-cli": "^4.0.0", "@angular/language-service": "^4.0.0", "@types/jasmine": "~2.5.53", "@types/jasminewd2": "~2.0.2", "@types/node": "~6.0.60", "codelyzer": "~3.0.1", "jasmine-core": "~2.6.2", "jasmine-spec-reporter": "~4.1.0", "karma": "~1.7.0", "karma-chrome-launcher": "~2.1.1", "karma-cli": "~1.0.1", "karma-coverage-istanbul-reporter": "^1.2.1", "karma-jasmine": "~1.1.0", "karma-jasmine-html-reporter": "^0.2.2", "protractor": "~5.1.2", "ts-node": "~3.0.4", "tslint": "~5.3.2", "typescript": "~2.3.3", .... - 方法中,您应该提供基类的所有成员。如果有许多成员,您也可以使用反射来执行此操作:

CloneBaseVehicle

Vehicle CloneBaseVehicle(Vehicle v) { Tractor t; switch v.Type { case Vehicles.Tractor: t = new Tractor(); case Vehicles.Car: t = new Car(); case Vehicles.Motorcycle: t = new Motorcycle(); } // now copy the common properties t.MyProperty = v.MyProperty; t.AnotherProperty = v.AnotherProperty; return t; } public Vehicle CloneVehicle (Vehicle v) { var newVehicl = CloneBaseVehicle(); switch(v.Type) { case(Vehicles.Tractor): var tractor = newVehicle as Tractor; tractor.TractorCapacity = 50 ; break; case Car: ... break; } return newVehicle; } 的基于反射的方法可能如下所示:

CloneBaseVehicle

无论您选择哪两种方法,都应该注意,从现有Vehicle CloneBaseVehicle(Vehicle v) { Tractor t; switch v.Type { case Vehicles.Tractor: t = new Tractor(); case Vehicles.Car: t = new Car(); case Vehicles.Motorcycle: t = new Motorcycle(); } var properties = typeof(Vehicle).GetProperties(); foreach(var p in properties) p.SetValue(t, v.GetValue(p)); return t; } 创建Tractor时,您当然会丢失仅存在于{{1}中的所有特殊信息}}