【问题标题】:Using type constraints from inherited interface gives implicit reference conversion error使用继承接口的类型约束会导致隐式引用转换错误
【发布时间】:2020-05-05 14:21:26
【问题描述】:

我有这种类型约束

where TLookup : ILookupable<ILookup>

我正在为类型传递这个接口

public interface IEmployeeProxy : ILookupableCode

你在哪里

public interface ILookupableCode : ILookupable<ILookupCode>

public interface ILookupable<T> where T : ILookup
{
    Task<IEnumerable<T>> LookupByNameAsync(string name, int take = 5, int skip = 0);

    Task<T> LookupByIdAsync(long id);
}

还有

public interface ILookupCode : ILookup

但是我收到了There is no implicit reference conversion 错误,我不知道为什么,因为对我来说IEmployeeProxy

IEmployeeProxy => ILookupableCode => ILookupable&lt;ILookupCode&gt; => ILookupable&lt;ILookup&gt;

我在这里做错了什么?为什么我会收到此错误?对我来说看起来我应该工作。

如果你想知道我为什么要这样做,是因为我希望 ILookupable 有一些返回 ILookup 的方法,但也有 ILookupableCodeILookupable 相同的方法返回ILookupCode 以及更多内容。

【问题讨论】:

  • 仅仅因为T1T2这两种类型表现出特定的继承/实现关系,并不暗示G&lt;T1&gt;G&lt;T2&gt;会表现出相同关系。 ILookupable&lt;ILookupCode&gt;ILookupable&lt;ILookup&gt;相关。有可能,但这取决于接口是否适合协方差/反方差。
  • @Damien_The_Unbeliever 可以更好地解释 ILookupable&lt;ILookupCode&gt;ILookupable&lt;ILookup&gt; 无关?在什么情况下会发生这种情况?
  • 默认为真。 List&lt;Bird&gt; 不是 List&lt;Animal&gt;,因为这样有人可以在其中粘贴 Giraffe
  • @Vencovsky 可能是this 对你有用。

标签: c# constraints type-constraints


【解决方案1】:

因此解决此问题的方法是将ILookupable 的签名更改为ILookupable&lt;out T&gt;,但这带来了另一个问题,我的方法需要返回一个接口类型。所以这使得不可能有一个返回类型为 Task&lt;T&gt; 的方法。

唯一的解决方法是使用this third party implementation of ITask

【讨论】:

    猜你喜欢
    • 2013-06-30
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-23
    • 2022-03-17
    相关资源
    最近更新 更多