[英]Derived classes with derived properties
我有兩個都從基類X派生的類。基類包含類T的一個屬性。X的兩個子類都應包含一個從T派生的屬性。
我想實現的是在基類X中聲明T的一個屬性,並在多種方法中使用它,而在X的派生類中使用T的相同屬性,但將其識別為T的派生類。 ,這樣我就不必在每次使用它時都進行投射。
我的解決方案之一是僅從基類中刪除該屬性,然后為X的每個派生類復制方法,但這將無法達到使用繼承的目的。
這樣的事情可以實現嗎?
internal class TestObject
{
public string ID;
public XObject obj;
//....
}
internal class TestDocument : TestObject
{
public XDocument obj; //<--- want to be able to call obj in my methods
//as if it were an XDocument type but relate to the obj property in the base class
//....
}
internal class XObject
{
//....
}
internal class XDocument : XObject
{
//....
}
泛型應該為您工作:
class Base<T> where T: MyType
{
T MyProperty { get; set; }
public void DoSomething()
{
// do something with MyProperty
}
}
其中MyType
是Base
屬性的基類。
然后,在派生類中,您可以定義通用約束,例如
class Derived : Base<DerivedType>
{
}
現在, Derived
的實例具有DerivedType
類型的MyProperty
屬性,而不是MyType
類型。
因此,在您的情況下, TestObject
應該與此類似:
internal class TestObject<T> where T: XObject
{
public string ID;
public T obj;
//....
}
internal class TestDocument : TestObject<XDocument>
{
// obj is here of type XDocument
}
使屬性的類型成為基類的通用參數:
class PropertyTypeBase { }
class PropertyTypeA : PropertyTypeBase { }
class Base<T> where T : PropertyTypeBase
{
public T Property { get; }
}
class Foo : Base<PropertyTypeA>
{
public Foo()
{
PropertyTypeBase x = Property;
PropertyTypeA a = Property;
}
}
最簡單的方法是使基類成為通用類,並限制要從某個類派生的通用參數:
class BaseProp { }
class DerivedPropA: BaseProp { }
class DerivedPropB : BaseProp { }
abstract class X<T>
where T: BaseProp
{
public T Value { get; set; }
public abstract void With(T value);
}
class A : X<DerivedPropA>
{
public override void With(DerivedPropA value)
{
this.Value = value;
}
}
class B : X<DerivedPropB>
{
public override void With(DerivedPropB value)
{
this.Value = value;
}
}
通過使用泛型,這是可能的。
首先,讓我解釋示例類。 假設這些是您的屬性:
public class BaseHead {}
public class OrganicHead : BaseHead {}
public class CyborgHead : BaseHead {}
現在,您想在您的人員類上實現這些負責人:
public class BaseCreature {}
public class OrganicCreature : BaseCreature {}
public class CyborgCreature : BaseCreature {}
解決方案:
public class BaseCreature<THead> where THead : BaseHead
{
public THead Head { get; set; }
public BaseCreature(THead head)
{
this.Head = head;
}
}
BaseCreature
通用 THead
類型限制為僅允許BaseHead
或從BaseHead
派生的BaseHead
但是,我們還想確保正確的生物(有機體/半機械人)僅使用正確的頭部(有機體/半機械人)。 這可以通過從具有特定泛型類型的BaseCreature
派生來完成:
public class OrganicCreature : BaseCreature<OrganicHead>
{
public OrganicCreature(OrganicHead head) : base(head)
{
}
}
CyborgCreature
是類似的。
假設您想讓每個生物都可以使用每種類型的頭部。 如果這就是您想要的,那么您需要使通用參數保持通用:
public class OrganicCreature<THead> : BaseCreature<THead> where THead : BaseHead
{
public OrganicCreature(THead head) : base(head)
{
}
}
CyborgCreature
是類似的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.