C#定义不同通用类型的元素列表,但所有元素都具有相同的基本类型

问题描述

我具有以下结构:

public interface IFoo
{
}

public interface IFoo2 : IFoo
{
}

public interface IBar
{
}

public interface IQux<in TFoo,in TBar>
    where TFoo : IFoo
    where TBar : IBar
{
    void normalize(TFoo a,TBar b);
}

public interface IGamma : IQux<IFoo2,IBar>
{
}

public class Gamma : IGamma
{
    public void normalize(IFoo2 a,IBar b)
    {
        // do something with a and b
    }
}

我也有:

  • 实现IFoo的所有扩展的类,我们可以调用FooImpl
  • 实现IBar的所有扩展的类,我们可以调用BarImpl
  • IQux的更多扩展,其中我定义了泛型的类型,例如IGamma

现在,我想要一个IQux的列表,并为每个元素调用方法normalize,该方法的参数为FooImpl的实现和BarImpl的实现。

但是,如果我按照以下方式定义列表,并且使用方法AddQux向列表中添加新元素,则会收到以下错误

错误CS1503参数1:无法从指令'<namespace>.IQux<TFoo,TBar>' to '<namespace>.IQux<<namespace>.IFoo,<namespace>.IBar>'中的list.Add(c);转换

public class Builder
{
    private IList<IQux<IFoo,IBar>> list = new List< IQux<IFoo,IBar> >();

    public void AddQux<TFoo,TBar>(IQux<TFoo,TBar> qux)
        where TFoo : IFoo
        where TBar : IBar
    {
        list.Add(qux);
    }
}

关于如何解决它的任何想法?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)