【问题标题】:Is this impossible given intra/contra/covariance?考虑到内部/反向/协方差,这是不可能的吗?
【发布时间】:2019-07-17 16:12:42
【问题描述】:

我想要达到的目标如下。

我有一个类似

的界面
interface ISomething<T>
{
   void Input(T item);

   IEnumerable<T> Outputs();
}

和类似的层次结构

interface IFoo { }
interface IBar : IFoo { }
interface IBaz : IFoo { }

我希望能够通过ISomething&lt;IFoo&gt; 引用ISomething&lt;IBaz&gt;ISomething&lt;IBar&gt;,这样我就可以编写类似的方法

void ProcessFoos(ISomething<IFoo> somethings)
{
    foreach (var something in somethings)
    {
       var outputs = something.Outputs();
       // do something with outputs
    }
}

其中somethings 可以是ISomething&lt;IBar&gt;s 和ISomething&lt;IBaz&gt;s 的组合。

考虑到语言限制,这不可能吗?

如果没有,我该如何重新设计?

编辑:这是我所说的更好的例子

public class Program
{
    public static void Main()
    {
        IBar<IX> x = new Bar<Y>() { };
        // ^^^ Cannot implicitly convert type 'Bar<Y>' to 'IBar<IX>'. An explicit conversion exists (are you missing a cast?)
    }
}

public interface IBar<T> where T : IX
{
    void In(T item);

    T Out { get; }
}

public class Bar<T> : IBar<T> where T : IX
{
    public void In(T item) { }

    public T Out { get { return default(T); } }
}

public interface IX { }

public class Y : IX { }

【问题讨论】:

  • 我也尝试过这样做,但没有成功,但如果您将接口声明为in,然后在您的代码类中显式实现它,它确实有效。
  • @theMayer 看到我的编辑
  • 您的编辑是一个全新的问题。

标签: c# .net oop inheritance


【解决方案1】:

您将somethings 视为IEnumerable,但事实并非如此。如果你想遍历输出,可以这样调用。

void ProcessFoos(ISomething<IFoo> something)
{
  foreach (var output in something.Outputs())
  {
    if(output is IBar)
    {
      // do something IBar related
    }
    else if(output is IBaz)
    {
      // do something IBaz related
    }
  }
}

如果somethings 应该是IEnumerable,请像这样更改ProcessFoos 的签名:

void ProcessFoos(IEnumerable<ISomething<IFoo>> somethings)
{
  foreach (var something in somethings)
  {
    var outputs = something.Outputs();
    var barOutputs = outputs.OfType<IBar>();
    var bazOutputs = outputs.OfType<IBaz>();

    // do something with outputs
  }
}

这对我有用。

如果这对您不起作用,请提供您看到的错误和/或说明您正在尝试但无法实现的目标。

【讨论】:

  • 克里斯托弗,看我的编辑
猜你喜欢
  • 2011-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-05
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多