gpt4 book ai didi

c# - 类中没有泛型引用的泛型类型方法

转载 作者:行者123 更新时间:2023-11-30 22:06:31 25 4
gpt4 key购买 nike

我有一个类有一些方法,其中两个(ADD 和 UPDATE)想要通用。

这是我的类(class):

public class CatalogRepository : ICatalogRepository
{
public CatalogRepository(DbContext dbContext)
{
if (dbContext == null)
throw new ArgumentNullException("dbContext");
DbContext = dbContext;
}

private DbContext DbContext { get; set; }

#region Generic ADD and UPDATE

public void Add<T>(T entity) where T : DbSet
{
DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
if (dbEntityEntry.State != System.Data.Entity.EntityState.Detached)
{
dbEntityEntry.State = System.Data.Entity.EntityState.Added;
}
else
{
DbContext.Set<T>().Add(entity);
}
}

public void Update<T>(T entity) where T : DbSet
{
DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
if (dbEntityEntry.State == System.Data.Entity.EntityState.Detached)
{
DbContext.Set<T>().Attach(entity);
}
dbEntityEntry.State = System.Data.Entity.EntityState.Modified;
}

#endregion

#region SetupSensor


public IEnumerable<SetupSensor> GetSetupSensors(string masterEntity)
{
return DbContext.Set<SetupSensor>().Where(c => c.MasterEntity == masterEntity).ToList();
}

public IEnumerable<SetupSensor> ReadOnlySetupSensors(string masterEntity)
{
return DbContext.Set<SetupSensor>().AsNoTracking().Where(c => c.MasterEntity == masterEntity).ToList();
}

public SetupSensor GetSetupSensor(int sensorId)
{
return DbContext.Set<SetupSensor>().Where(c => c.SensorId == sensorId).FirstOrDefault();
}


#endregion
}

这是接口(interface)实现:

public interface ICatalogRepository
{
SetupSensor GetSetupSensor(int sensorId);
IEnumerable<SetupSensor> GetSetupSensors(string masterEntity);
void Add<T>(T entity);
void Update<T>(T entity);
}

当我构建时,我在两种通用方法上遇到以下错误:

The constraints for type parameter 'T' of method 'CatalogRepository.Add<T>(T)' must match the constraints for type parameter 'T' of interface method 'ICatalogRepository.Add<T>(T)'. Consider using an explicit interface implementation instead.

关于如何处理这个的任何线索?

最佳答案

好吧,这个错误是不言自明的。实现接口(interface)时,必须完全按照定义的方式实现其所有成员。由于您在接口(interface)中不存在的实现中引入了额外的通用约束,因此实现与接口(interface)不匹配。

有两种方法可以解决这个问题:将约束添加到接口(interface),或者从实现中删除它们。

作为旁注,您可能需要考虑使整个接口(interface)通用,即像这样声明它:

// you may or may not want to have the constraint here
public interface ICatalogRepository<T> where T : DbSet
{
// sensor methods
void Add(T entity);
void Update(T entity);
}

关于c# - 类中没有泛型引用的泛型类型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23593553/

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