【问题标题】:Problem with Interface Implementation When using Inheritance使用继承时接口实现的问题
【发布时间】:2020-07-27 11:44:54
【问题描述】:

我创建了 IShallowCloneable 接口来为我的所有类创建类的浅表副本,但是通过继承它无法正常工作。

看看Main方法,node2返回的是Point3D对象而不是Node。

详情

  • Point2D 是基类
  • Point3D 类派生自 Point2D 类
  • 节点 类派生自 Point3D 类
using System;

namespace ConsoleAppTest
{
    internal static class Program
    {
        private static void Main()
        {
            try
            {
                var node = new Node(1, 0, 0, 0);
                var node2 = node.ShallowClone();//this code is returing Point3D Object instead of Node
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                Console.ReadLine();
            }
        }
    }

    public interface IShallowCloneable<T>
    {
        T ShallowClone();
    }

    public class Point2D : IShallowCloneable<Point2D>
    {
        public int X { get; set; }
        public int Y { get; set; }

        public Point2D()
        {
        }
        public Point2D(int x, int y)
        {
            X = x;
            Y = y;
        }

        public Point2D ShallowClone()
        {
            return new Point2D(X, Y);
        }
    }
    public class Point3D : Point2D, IShallowCloneable<Point3D>
    {
        public int Z { get; set; }

        public Point3D()
        {
        }
        public Point3D(int x, int y,int z):base(x,y)
        {
            Z = z;
        }
        new public Point3D ShallowClone()
        {
            return new Point3D(X, Y,Z);
        }
    }

    public class Node:Point3D, IShallowCloneable<Node>
    {
        public int Id { get; set; }
        public Node()
        {

        }
        public Node(int id,int x, int y, int z):base(x,y,z)
        {
            Id = id;
        }

        Node IShallowCloneable<Node>.ShallowClone()
        {
            return new Node(Id,X, Y, Z);
        }
    }
}

【问题讨论】:

    标签: c# inheritance interface


    【解决方案1】:

    因为对于Node,您已将IShallowCloneable&lt;Node&gt; 实现为explicit interface,因此只有在您转换为它时才会起作用:

    // prints Node
    Console.WriteLine(((IShallowCloneable<Node>)node).ShallowClone().GetType().Name); 
    

    如果您希望它表现得像Point3D,您需要像在那里一样实现它(使用new 关键字隐藏继承的Point2D 实现)。

    【讨论】:

      【解决方案2】:

      所以如果你想显式使用 ShallowClone 方法而不改变类

      var node = new Node(1, 0, 0, 0);
      var node2 = ((IShallowCloneable<Node>)node).ShallowClone();
      

      或者如果你想要隐式实现,你必须像这样在节点类中修改 ShallowClone() 方法实现

      new public Node ShallowClone()
      {
          return new Node(Id, X, Y, Z);
      }
      

      其他参考

      C# Interfaces. Implicit implementation versus Explicit implementation

      【讨论】:

      • 请解释为什么这是答案
      • @ColinM 现在,我的解释可以了吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 2016-03-07
      相关资源
      最近更新 更多