【问题标题】:C# OOP specific params while extending class扩展类时的 C# OOP 特定参数
【发布时间】:2021-01-05 15:10:39
【问题描述】:

我有一个 ClassA 类,它有一个类型为 AttA 的受保护属性、一个从 ClassA 扩展的 ClassB 类和一个从 AttA 扩展的 AttB 类。

在 ClassA 类中,我想使用属性 AttA,但在 ClassB 类中,我想使用更具体的属性 AttB。

有办法吗?

class ClassA
{
    protected AttA att;

    public void MyMethod()
    {
        // using att as AttA
    }
}
class ClassB : ClassA
{
    public override void MyMethod()
    {
         // Want to use att as AttB (if possible without downcasting)
    }
}

谢谢。

【问题讨论】:

    标签: c# class oop extends


    【解决方案1】:

    一个简单的方法是使用new关键字:

    class ClassA
    {
      protected AttA att;
      public virtual void MyMethod()
      {
      }
    }
    
    class ClassB : ClassA
    {
      new protected AttB att;
      public override void MyMethod()
      {
      }
    }
    
    class AttA
    {
    }
    
    class AttB : AttA
    {
    }
    

    但这可能会导致使用多态性时出现问题,因为编写:

    var b = new ClassB();
    
    //b.att is type of AttB here
    
    var a = (ClassA)b;
    
    //a.att is type of AttA here and it is not the same variable
    

    事实上,有两个字段 att 取决于您操作的类型,因此在类实现中要小心,尤其是在从子类调用基成员时。

    由于该字段受到保护,这个问题是有限的。

    相反,这可能正是我们所需要的。

    https://docs.microsoft.com/dotnet/csharp/language-reference/keywords/new-modifier


    我试图找到一个泛型解决方案,但由于 C# 不支持真正的泛型多态性,而且我们不能将泛型类型参数限制在一种类型上用于一种类类型,据我所知,这是不可能的 -或者它需要使用反射编写一些代码,除非有必要,否则这里可能会过度设计(因此可能在暴露所需多态类型的类层次结构之间具有相同的变量)。

    【讨论】:

    • 如果我错了请纠正我,但ClassB 中的attClassA 中的对象完全不同。
    • 确实,我只是对此添加了解释。
    • 轻微更正:OP 状态:"...从 AttA 扩展的类 AttB"
    • 你不能通过在ClassB中写base.att = this.att;来避免这个陷阱吗?
    • "是的",我们可以在子类中为att 设置器中使用它,但在母类中不能。因此,这根本不干净也不一致。因此 NO 因为母类不知道子类(或者我们需要使用“硬全局且可能滞后”的反射,对于这种情况,我更喜欢提到的干净的通用解决方案,但它需要一些开发人员来检查并在运行时强制转换类型)。
    猜你喜欢
    • 2016-07-04
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-09
    • 1970-01-01
    相关资源
    最近更新 更多