我正在尝试创建对我创建的 C# .NET 7 函数的调用,该函数将接受多个使用相同接口的不同类。
我创建了以下接口类:
namespace ConsoleApp2.Models;
public interface CommonInterfaces<T> where T : class
{
public List<T> items { get; set; }
}
public interface CommonInterface
{
DateTime? createdOn { get; set; }
DateTime? modifiedOn { get; set; }
}
然后我根据接口创建了类:
namespace ConsoleApp2.Models;
public class Agents : CommonInterfaces<Agent>
{
public List<Agent> items { get; set; }
}
public partial class Agent : CommonInterface
{
public DateTime? createdOn { get; set; }
public DateTime? modifiedOn { get; set; }
public DateTime? lastModified { get; set; }
public string? dataDescription { get; set; }
public bool? isDeleted { get; set; }
public string? primaryKey { get; set; }
}
我创建了一个函数:
static async Task ProcessAgentSync<S, T>()
where S : CommonInterface where T : CommonInterfaces<CommonInterface>, new()
{
T data = new T();
}
当我尝试打电话给
ProcessAgentSync
时:
await ProcessAgentSync<Agent, Agents<Agent>>();
我收到错误:
非泛型类型“代理”不能与类型参数一起使用
嗯,这个错误相当明显。
Agents
不是泛型类,它仅继承自泛型接口。所以 Agents<Agent>
不是有效类型。
所以我们将其更改为
ProcessAgentSync<Agent, Agents>
。但这仍然行不通。 Agents
是 CommonInterfaces<Agent>
,但不是 CommonInterfaces<CommonInterface>
。
这可能是一个协方差或逆变问题,但该示例没有做任何有意义的事情,因此很难提供建议。
也许您应该将常用界面更改为:
public interface CommonInterfaces<out T> where T : class
{
public IReadOnlyList<T> Items { get; }
}
或者
public interface CommonInterfaces
{
public List<CommonInterface> items { get; set; }
}
要么可以解决您的问题,但是如果不了解您要解决的问题,就很难判断。我一般会警告不要尝试编写过于通用的代码。很容易得到非常复杂且难以使用的代码。