[英]Generic class definition with both generic type constraint and inherited type?
[英]Alternative to generic inherited class to constraint an inherited property to be a child of its base type itself
我想将继承的类的成员限制为特定类型。 我知道我可以使用泛型类来做到这一点,但似乎比应该做的要复杂得多。 所以,这是一个例子。
public class Shape
{
public Texture texture { get; set; }
}
public class Texture { ... }
public class SpecficTexture : Texture { ... }
public class SpecificShape : Shape
{
public SpecificShape()
{
texture = new SpecficTexture();
}
}
本质上,就我而言,我需要实现类SpecificShape。 一切都很好,但是SpecificShape中的纹理属性不称为特定纹理。 从SpecificShape,它需要这样被知道。 显然,我可以改用以下类。
public class Shape2<T> where T : Texture
{
public T texture { get; set; }
}
public class SpecifShape2 : Shape2<SpecficTexture> { ... }
我看到了两种解决方案。 我要么去我的团队切换以使Shape成为通用类,要么在需要时将纹理投射到SpecificTexture。 还有其他办法吗?
我不喜欢强制转换的想法,对我来说似乎并不优雅,而且我担心不得不多次执行性能问题。 同时,我不确定更改已实施的内容是否合理。
您可以在Shape
中将texture
属性设为虚拟,在SpecificShape
中将其覆盖并将铸造限制在一个特定位置:
public class Shape
{
public virtual Texture texture { get; set; }
}
public class SpecificShape : Shape
{
public SpecificTexture specificTexture { get; set; }
public override Texture texture
{
get { return specificTexture; }
set
{
if (value is SpecificTexture specificValue) //this is the only place we have to have a cast
{
specificTexture = specificValue;
}
else
{
//handle error, throw exception, Debug.Assert, or something
}
}
}
public SpecificShape()
{
specificTexture = new SpecificTexture();
}
}
每当需要在SpecificShape类中使用SpecificTexture时,都可以简单地使用specificTexture
属性而不是texture
。
此外,如果父Shape
类实际上不需要texture
属性设置器(也许在构造函数中仅设置一次texture
属性?),则只需摆脱设置器,就可以避免进行任何强制转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.