【发布时间】:2017-01-17 14:03:39
【问题描述】:
我认为我在这里遇到了基本的 OOP 误解:
(顺便说一句,这些是 Entity Framework 6 类,以防您对“虚拟”感到惊讶)
public class WeaponUsed : HistoryEvent
{
public virtual Player Target { get; set; }
public virtual GameCountry Country { get; set; }
//Victims: Troops or Pops
public ICollection<Victim> Victims { get; set; }
public bool HasMoreWeaponsLeft { get; set; }
}
受害者可以是“部队”对象或“人口”对象。受害者类别必须是什么样子?我可以使用 2 个属性并将未使用的属性设置为“null”,如下所示:
public class Victim
{
public virtual Troop TroopVictim { get; set; }
public virtual Population PopVictim { get; set; }
}
但这不可能是最好的解决方案,对吧? 我想确定受害者可以是要么部队或人口。
我也想过通过setter来做:
public ICollection<object> Victims { get;
set
{
if (value.GetType() == typeof(Troop) || value.GetType() == typeof(Population))
Victims.Add(value);
}
}
但我仍然不认为这是最好的方法,或者它可能是...... 有没有更好、更清洁的?
【问题讨论】:
-
您可以尝试使用
enum,例如:enum Victim { Troop, Population }。 -
我知道,但我需要存储在对象中的额外信息。 “名字”本身是不够的。
-
您需要存储哪些额外信息?
-
基类应该是
victim。从victim派生Troop和Population。 -
IMO,这是你能得到的最好的。你也可以试试table per hierarchy mapping
标签: c# entity-framework class oop properties