我认为我在这里遇到了一个基本的OOP误解:
(这些是实体框架6课程顺便说一下,如果您对#34;虚拟&#34感到惊讶;)
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; }
}
受害者可以是&#34;部队&#34;对象,或者&#34;人口&#34;宾语。受害者阶层的样子是什么样的?我可以使用2个属性并将未使用的属性设置为&#34; null&#34;像这样:
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);
}
}
但我仍然不认为这是最好的方式,或者可能是...... 有更好,更清洁的吗?
答案 0 :(得分:1)
您可以使用界面。
public class WeaponUsed : HistoryEvent
{
public virtual Player Target { get; set; }
public virtual GameCountry Country { get; set; }
//Victims: Troops or Pops
public IVictim Victims { get; set; }
public bool HasMoreWeaponsLeft { get; set; }
}
public interface IVictim {
// common methods and properties for PopVictim and TroopVictim
int Number {get;}
}
public class TroopVictim : IVictim {
// TroopVictim will be enforced to have IVictim methods and proprieties
public int Number{ get {return 1; } }
}
public class PopVictim : IVictim {
// PopVictim will be enforced to have IVictim methods and proprieties
public int Number{ get {return 100; } }
}
用法:
Console.WriteLine(weapon.Victims.Number)
答案 1 :(得分:0)
界面交配!
public interface IVictim
{
string SharedProp { get; set; }
}
public class TroopVictim : IVictim
{
public string SharedProp { get; set; }
public string TroopProperty { get; set; }
}
public class PopVictim : IVictim
{
public string SharedProp { get; set; }
public string PopProperty { get; set; }
}
public class MyGenericVictim
{
//Optional Property
public bool? IsTroopVictim
{
get
{
if (Victim == null) return null;
return Victim.GetType() == typeof(TroopVictim);
}
}
public IVictim Victim { get; set; }
}
public class UseMyOfVictim
{
public void Bar()
{
Foo(new MyGenericVictim
{
Victim = new TroopVictim(),
});
}
public void Foo(MyGenericVictim myvic)
{
//Function doesnt know TroopVic or PopVic
TroopVictim resolvedTroopVic;
PopVictim resolvedPopVictim;
if (myvic.Victim.GetType() == typeof(TroopVictim))
{
resolvedTroopVic = (TroopVictim) myvic.Victim;
}
else if (myvic.Victim.GetType() == typeof(PopVictim))
{
resolvedPopVictim = (PopVictim) myvic.Victim;
}
string success = resolvedPopVictim.PopProperty;
success = resolvedTroopVic.TroopProperty;
}
}