什么是“类型T必须是引用类型才能将其用作参数”?意思? [英] What does "The type T must be a reference type in order to use it as parameter" mean?
问题描述
我正在尝试在C#/ MVC / Entity Framework应用程序上创建通用控制器。
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> ;
和 T_Instance
行有编译器错误。
However the DbSet<T>
and T_Instance
line has a compiler error.
T
类型必须是引用类型,才能将其用作参数。
The type
T
must be a reference type in order to use it as parameter.
当我将其约束为类
时,它就解决了。
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.
推荐答案
如果您查看 Db< TEntity>
:
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必须是引用类型才能将其用作参数”?意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!