gpt4 book ai didi

c# - 如何在具有继承性的不可变数据模型中避免代码重复?

转载 作者:行者123 更新时间:2023-11-30 22:39:30 24 4
gpt4 key购买 nike

给定一个类层次结构,例如:

Entity { id, name, position }
Combatant : Entity { health, strength }
Avatar : Combatant { connection }

它们都是不可变的。

为了在一个实体上实现“移动”,我可以返回一个具有不同位置的新实体。

Entity Move(p) { return new Entity(id, name, p); }

但是,如果我在头像上调用“移动”,我将得到一个实体,而不是头像。所以我必须在所有不可变类上实现“移动”。有没有办法避免这种情况或更好的解决方案?

最佳答案

你可以用泛型来解决这个问题,为了简单起见,我假设所有属性都有 protected setter:

Entity<InheritingType>
where InheritingType : Entity<InheritingType>
{

public T Move(Position newPosition)
{
T result = this.Clone();
result.Position = newPosition;
return result;
}

private T Clone()
{
//create a new instance of ourselves using reflection
//i.e. reflect all the protected properties in the type (or fields if you don't want even protected properties) , and set them
//you could also have the Clone method be abstract and force it's implementation in all inheriting types

}
}

为了让当前类型保持原样,您可以为每个具体类型做一个简单的泛型基础继承:

Entity : Entity<Entity>{}
Combatant<InheritingType> : Entity<InheritingType>{}
Combatant : Combatant<Combatant>{}
Avatar : Combatant<Avatar>{}

有关深度克隆的示例,您可以 follow this link尽管我应该指出,如果性能很重要,最好要求每个继承类重写此方法并将它们自己的属性添加到克隆过程中。

关于c# - 如何在具有继承性的不可变数据模型中避免代码重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5690227/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com