gpt4 book ai didi

c# - 用泛型和约束覆盖虚方法

转载 作者:太空狗 更新时间:2023-10-29 17:49:24 25 4
gpt4 key购买 nike

我正在尝试覆盖 DbContext.Set<TEntity>() method .

它的签名是:

public virtual DbSet<TEntity> Set<TEntity>() where TEntity : class

首先我尝试了这个:

public override DbSet<TEntity> Set<TEntity>()
{
return base.Set<TEntity>();
}

...但是我得到了错误:

The type 'TEntity' must be a reference type in order to use it as parameter 'TEntity' in the generic type or method 'System.Data.Entity.DbContext.Set()'

...所以我尝试指定它是一个引用类型:

public override DbSet<TEntity> Set<TEntity>() where TEntity: class
{
return base.Set<TEntity>();
}

...我现在得到:

Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly.

...如果我把它拿走,我又回到了第一个错误。

那么 C# 编译器要我做什么?

最佳答案

好吧,这很蹩脚......我使用的是 Entity Framework 6.0.0 版。

在 6.0.0 中(在深入研究 history of the project on Code Plex 之后,我发现 Set<TEntity>() 当时不是 virtual

遗憾的是编译器不能这么说,而不是让我四处走动。

无论如何,将 Entity Framework 更新到 6.1.x( virtual),解决了问题;

Update-Package EntityFramework

关于c# - 用泛型和约束覆盖虚方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25821526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com