使用派生类类型作为基类的通用操作的参数 [英] Use derived class type as parameter of generic action of base class
问题描述
我想通过委托来操纵实例,这是类本身的属性.委托的参数应该始终是实例本身(即使在派生类中也是如此!).
I want to manipulate an instance by a delegate, which is a property of the class itself. The parameter of the delegate should always be the instance itself (even in derived classes!).
请参见下面的代码.我知道代码没有编译,因为我必须将car1转换为type,我正在寻找不进行转换的解决方案.
See code below. I know that the code is not compiling because I have to cast car1 to type car, I'm looking for a solution without casting.
代码
static void Main(string[] args)
{
var car = new Car();
car.VehicleManipulator = car1 => car1.SomeInt++;
car.ManipulateVehicle();
Console.WriteLine("end");
Console.ReadLine();
}
internal class Vehicle
{
public Action<Vehicle> VehicleManipulator { get; set; }
public void ManipulateVehicle()
{
this.VehicleManipulator(this);
}
}
internal class Car : Vehicle
{
public int SomeInt { get; set; }
}
更改了密码!
我的问题是,有没有一个好的解决方案可以仅在基类中处理所有这些问题,但是在操作中我想使用派生类而不进行转换.
My question is, is there a good solution to handle all this just in the base class, but in the action I want to use the derived classes without casting.
推荐答案
如果要避免强制转换,请使Vehicle通用,如:
If you want to avoid casting, make Vehicle generic like:
class Vehicle<T> where T : Vehicle {
Action<T> ManipulateVehicle { get; set; }
}
class Car : Vehicle<Car> {
int SomeInt { get; set; }
}
看起来有点怪异,但是这意味着如果您有汽车实例,则操纵器可在汽车上工作,如果您有卡车,则其可在卡车上工作,依此类推.车辆可能应该是抽象的.
It looks a little weird but it means if you have an instance of car the manipulator works on cars and if you have a truck it works on trucks and so on. Vehicle should probably be abstract.
这篇关于使用派生类类型作为基类的通用操作的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!