问题描述
我正在尝试在我的 C#/MVC/实体框架应用程序上创建一个通用控制器.
I'm trying to create a generic controller on my C#/MVC/Entity Framework application.
public class GenericRecordController<T> : Controller
{
private DbSet<T> Table;
// ...
public action()
{
// ...
db.Entry(T_Instance).State = System.Data.Entity.EntityState.Modified;
}
}
但是 DbSet
和 T_Instance
行有一个编译器错误.
However the DbSet<T>
and T_Instance
line has a compiler error.
类型 T
必须是引用类型才能将其用作参数.
当我将其约束为 class
时,它就解决了.
When I constrain it as a class
, it was solved.
Controller where T : class
错误是什么意思?我不是在寻求解决方案,我想了解为什么会发生此错误以及为什么将其约束为 class
可以解决它.
What does the error mean? I'm not asking for a solution, I would like to understand why this error occurs and why constraining it as a class
solves it.
推荐答案
如果看DbSet
的定义:
public class DbSet<TEntity> : DbQuery<TEntity>, IDbSet<TEntity>, IQueryable<TEntity>, IEnumerable<TEntity>, IQueryable, IEnumerable, IInternalSetAdapter
where TEntity : class
因为它有一个类型约束
泛型类型必须是 class
那么你必须用一个也匹配这个条件的类型来初始化它:
Because it has a type constraint
that the generic type must be a class
then you must initialize it with a type that also matches this condition:
public class GenericRecordController<T> : Controller where T : class
{ ... }
这篇关于“类型 T 必须是引用类型才能将其用作参数"是什么意思?意思是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!