首页 > 解决方案 > 当子类从父类继承时,有没有办法为继承的字段使用不同的数据类型来添加更多功能?

问题描述

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

我需要创建两个具有一些相似性但又足够不同以保证拥有不同类的对象。所以我认为为他们设置一个基类是合适的。我在基类“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
}

有没有办法让我通过继承或接口来实现这一点?

标签: c#oopinheritance

解决方案


这回答了你的问题了吗?

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>
        {

        }

推荐阅读