C#. What “The type T must be a reference type in o

2019-04-23 18:08发布

问题:

I'm trying to create a generic controller on my MVC C# Entity Framework Application.

public class GenericRecordController<T> : Controller
{
    private DbSet<T> Table;
    // ... 

    public action(){
        // ... 
        db.Entry(T_Instance).State = System.Data.Entity.EntityState.Modified;
    }
}

However the DbSet<T> and T_Instance line has a compiler error.

The type T must be a reference type in order to use it as parameter.

When I constraint it for a class

Controller where T : class

it was solved.

What does the error above means?

I'm not asking for a solution. I would like to understand why this error occurs and why constraint it for a class solves it.

回答1:

If you look at the definition of Db<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
{ ... }


回答2:

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.