什么是“类型T必须是引用类型才能将其用作参数”?意思? [英] What does "The type T must be a reference type in order to use it as parameter" mean?

查看:568
本文介绍了什么是“类型T必须是引用类型才能将其用作参数”?意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆