“类型 T 必须是引用类型才能用作参数”是什么意思?

我试图在我的 C #/MVC/Entity Framework 应用程序上创建一个通用控制器。

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行有一个编译器错误。

类型 T必须是引用类型才能将其用作参数。

当我把它限制为 class时,它就解决了。

Controller where T : class

这个错误是什么意思?我不是要求一个解决方案,我想知道为什么会出现这个错误,为什么将它限制为 class可以解决它。

80177 次浏览

They apparently have a constraint on the generic type.

All you need to change is:

public class GenericRecordController<T> : Controller where T : class

This tells the compiler that only reference types may be supplied as a type for T.

If you look at the definition of DbSet<TEntity>:

public class DbSet<TEntity> : DbQuery<TEntity>, IDbSet<TEntity>, IQueryable<TEntity>, IEnumerable<TEntity>, IQueryable, IEnumerable, IInternalSetAdapter
where TEntity : 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
{ ... }

You can do it on just a method as well:

public bool HasKey<T>(T obj) where T : class
{
return _db.Entry<T>(obj).IsKeySet;
}