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

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

问题描述

我正在尝试在我的 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;
    }
}

但是 DbSetT_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.

当我将其约束为 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 必须是引用类型才能将其用作参数"是什么意思?意思是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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