【问题标题】:How can I return a more derived type from an interface?如何从接口返回更多派生类型?
【发布时间】:2014-06-27 00:23:09
【问题描述】:

我有一个接口可以转换我想要实现的数据网格:

public interface ITransformable<T>
{
    T Slice(int x, int y, int width, int height);
    T Slice(Rectangle value);
    T Transpose();
    T Flip(bool horizontal, bool vertical);
    T Rotate(bool clockwise);
}

所以我创建了一个这样做的类:

public class Mesh<T> : ITransformable<Mesh<T>>
{
    public Mesh<T> Transpose() { ... }
    /// etc
}

但是,在制作更衍生版本的网格时,我遇到了问题。例如,我有一个Heightmap 类,它是一个Mesh&lt;float&gt;。通过对 T 进行特定实现,这允许我使用运算符重载,因此我可以轻松地将两个高度图添加在一起,例如。但是当我实现它时

public class Heightmap : Mesh<float> { ... }

Heightmap 的 ITransformable 函数仍然返回一个网格,而不是一个高度图。有没有办法在Mesh 中实现基本行为,但在派生类中“更改”返回类型?我以为这是协方差的目的,但我似乎无法弄清楚。

【问题讨论】:

  • 如果你打算覆盖Transpose,你需要在Mesh&lt;T&gt;中设置virtual,然后在Heightmap中设置override Heightmap Slice(int x, int y, int width, int height) {...}。如果您已经尝试过,请在您的问题中显示错误消息或它不起作用的方式。
  • 你需要通过方法将派生对象创建到基类中,可能是Mesh&lt;T,TImpl&gt; : ITransformable&lt;TImpl&gt; where TImpl:Mesh&lt;T&gt;, new()
  • 即使接口调用返回Mesh&lt;T&gt;,实现仍然可以从Transpose 的覆盖版本返回Heightmap(尽管需要标记virtual)。如果调用者需要访问该类的特定属性/方法,则调用者需要强制转换为 Heightmap。
  • 看起来@luqui 有我想要的答案。只需覆盖该方法并返回 base.Transpose() 即可正确更改我想要的类型。我现在问起来很愚蠢,但至少它有效!
  • Kyle Baran:看起来你问的和你想要的不匹配......或者你的评论使用了错误的术语 - 你不能覆盖方法并更改返回类型......无论如何 -考虑发布答案。

标签: c# generics interface covariance


【解决方案1】:

请尝试以下代码,它应该像魅力一样工作。将方法/异常替换为您自己的实现。

  public interface ITransformable<T, out S> where S : ITransformable<T, S>
    {
        S Slice(int x, int y, int width, int height);
        S Slice(Rectangle value);
        S Transpose();
        S Flip(bool horizontal, bool vertical);
        S Rotate(bool clockwise);
    }

    public class Mesh<T, S> : ITransformable<T, S> where S : Mesh<T,S>, ITransformable<T, S>, new()
    {
        public S Slice(int x, int y, int width, int height)
        {
            throw new NotImplementedException();
        }

        public S Slice(Rectangle value)
        {
            throw new NotImplementedException();
        }

        public S Transpose()
        {
           //The following will work smoothly.
           S sObject = this.Slice(10, 20, 30, 40);
           return sObject;
        }
        public S Flip(bool horizontal, bool vertical)
        {
            throw new NotImplementedException();
        }

        public S Rotate(bool clockwise)
        {
            throw new NotImplementedException();
        }

    }

    public class Heightmap : Mesh<float, Heightmap>
    {

    }

    public class Program
    {
        static void Main()
        {
            Heightmap heightmap = new Heightmap();
            Heightmap map2 = heightmap.Transpose(); //This will work smoothly.
        }
    }

【讨论】:

    猜你喜欢
    • 2012-02-16
    • 2018-01-08
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    • 2019-11-05
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多