【问题标题】:Error CS1503 when casting covariant generic interface types转换协变泛型接口类型时出现错误 CS1503
【发布时间】:2021-05-16 11:10:15
【问题描述】:

使用 C# 9,我在尝试从实现某个接口的泛型类型转换为 Func 内的同一接口时遇到了 CS1503 错误,其中返回类型是协变的。

示例代码:

public interface ITest
{
    ...
}

public class Test
{
    private static readonly Dictionary<Type, Func<string, ITest>> constructors = new();

    public static void Register<T>(Func<string, T> constructor) where T : ITest
    {
        constructors.Add(typeof(T), constructor);
    }
}

错误出现在Add 方法中:Argument 1 cannot convert from Func&lt;string, T&gt; to Func&lt;string, ITest&gt;。 奇怪的是,如果那个接口是一个类,演员表工作得很好。

【问题讨论】:

    标签: c# generics covariance


    【解决方案1】:

    是的,这是与泛型协方差的预期行为,它与来自Func 的返回值的表示有关。

    T 受类约束时,运行时知道委托返回的值将始终是一个引用——因此它只需要为引用分配足够的空间,而不管实际 em> func 类型。

    T 通过接口约束但没有额外的“类”约束时,您可以传入一个返回值类型值而不是引用的委托。这打破了协方差假设的各种事物。

    但是,您可以仍然使用接口 - 只要您也使用 class 约束来约束 T。像这样更改您的方法签名,它会编译:

    public static void Register<T>(Func<string, T> constructor) where T : class, ITest
    

    有关表示(和身份)的更多信息,请参阅Eric Lippert's blog post on the topic 以及他的whole series on generic variance

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 2015-05-20
      • 1970-01-01
      相关资源
      最近更新 更多