当子类从父类继承时,是否有方法为继承的字段使用不同的数据类型来添加更多功能



当子类从父类继承时,是否有方法为继承的字段使用不同的数据类型,以在不同的子类中为字段添加更多功能?然后将这些子类用作一个可以用作函数中参数的单一数据类型?

我需要创建两个对象,它们有一些相似之处,但又足够不同,以保证拥有不同的类。所以我认为给他们上一个基础课是合适的。我在基类"ParentBase"中创建了两个道具,其中包含供子类使用的共享内容,子类需要为这些共享道具添加更多功能。

例如,ParentBase中的Settings字段应在Parent1和Parent2类中进行扩展,以满足它们自己的独特需求。我觉得我需要创建新的数据类型来扩展Parent1和Parent2类的Settings字段。

class ParentBase
{
public ChildA Settings { get; set; }
public ChildX MoreSettings { get; set; }
// lots of shared props here that won't be extended in inheriting classes
public void SomeFunction()
{
// The inheriting class's Settings and MoreSettings props should be available to access here
// even though their data types are different to the base class's Settings and MoreSettings
// data types
}
}
class Parent1 : ParentBase
{
public ChildB Settings { get; set; }
public ChildY MoreSettings { get; set; }
}
class Parent2 : ParentBase
{
public ChildC Settings { get; set; }
public ChildZ MoreSettings { get; set; }
}
class ChildA { // base props and methods in here }
class ChildB : ChildA { // Parent1 specific functionality }
class ChildC : ChildA { // Parent2 specific functionality }
class ChildX { // base props and methods in here }
class ChildY : ChildX { // Parent1 specific functionality }
class ChildZ : ChildX { // Parent2 specific functionality }

我还需要在基类之外创建函数,这些函数将接受Parent1或Parent2对象作为参数。例如:

public void Calculate(SomeSharedType Parent1/Parent2 instance)
{
// need to access the Settings and MoreSettings properties here, and the base class's Setting should suffice,
// although it would be nice to access the inheriting class's Settings and MoreSettings properties
}

有没有一种方法可以让我通过继承或接口来实现这一点?

这能回答您的问题吗?

class ParentBase<T,U>
{
public virtual T Settings { get; set; }
public virtual U MoreSettings { get; set; }
}
class Parent1 : ParentBase<ChildB, ChildY>
{
public override ChildB Settings { get; set; }
public override ChildY MoreSettings { get; set; }
}
class Parent2 : ParentBase<ChildC, ChildZ>
{
public override ChildC Settings { get; set; }
public override ChildZ MoreSettings { get; set; }
}

尽管您应该注意,只有当您想要更改属性行为时,覆盖才是必要的,但为了只更改类型,以下代码就足够了:

class ParentBase<T,U>
{
public T Settings { get; set; }
public U MoreSettings { get; set; }
}
class Parent1 : ParentBase<ChildB, ChildY>
{
}
class Parent2 : ParentBase<ChildC, ChildZ>
{
}

最新更新