我有几个类继承自像PeriodicWave
这样的泛型类。我想通过他们的基类来构建我的派生类(不确定它是否以正确的方式表达它)。我的课程是:
FooBasePolicy<TFooTarget>
然后我尝试以这种方式使用这些,
问题是我不知道TeamTarget是哪个。它可以是G或M.
public class FooTarget{}
public class GTeamTarget : FooTarget{}
public class MTeamTarget : FooTarget{}
public class FooBasePolicy{}
public class FooBasePolicy<TFooTarget> : FooBasePolicy where TFooTarget : FooTarget
{
public virtual TFooTarget SomeFooTarget { get;set; }
}
public class GTeamPolicy : FooBasePolicy<GTeamTarget>
{
public GTeamPolicy()
{
SomeFooTarget = new GTeamTarget();
}
}
public class MTeamPolicy : FooBasePolicy<MTeamTarget>
{
public GTeamPolicy()
{
SomeFooTarget = new MTeamTarget();
}
}
FromBinary实际上返回一个反序列化的对象。
但它完全可以投入FooBasePolicy<FooTarget> policy = null;
if (something.Equals("GTEAM"))
{
//This gives me an implicit conversion error. It can't cast.
policy = FromBinary(type, funnelData.Data) as FooBasePolicy<FooTarget>;
}
else if (something.Equals("MTEAM"))
{
policy = FromBinary(type, funnelData.Data) as FooBasePolicy<FooTarget>;
}
。但后来我想念FooBasePolicy
财产。
有什么想法吗?请帮忙。
答案 0 :(得分:1)
正如其他人所说,只需定义一个界面:
public interface IFooBasePolicy<out TFooTarget> {
TFooTarget SomeFooTarget { get; }
}
基类FooBasePolicy
现在看起来像:
public class FooBasePolicy<TFooTarget> : IFooBasePolicy<TFooTarget>
where TFooTarget : FooTarget {
public virtual TFooTarget SomeFooTarget { get; set; }
}
稍后您可以使用以下演员:
policy = ((IFooBasePolicy<FooTarget>)FromBinary(something));
简短说明:
FooBasePolicy<FooTarget>
不是FooBasePolicy<GTeamTarget>
GTeamTarget
是FooTarget
的子类型,因此FooBasePolicy<GTeamTarget>
是FooBasePolicy<FooTarget>
C#