【发布时间】: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<string, T> to Func<string, ITest>。
奇怪的是,如果那个接口是一个类,演员表工作得很好。
【问题讨论】:
标签: c# generics covariance