Why do I get “error: … must be a reference type” in my C# generic method?

前端 未结 3 1981
离开以前
离开以前 2020-12-05 13:30

In various database tables I have both a property and a value column. I\'m using Linq to SQL to access the database.

I\'m writing a method which returns a dictionary

相关标签:
3条回答
  • 2020-12-05 13:48
    public class TEntityRepository<TEntity> : EFRepository<TEntity> , ITEntityRepository<TEntity>
        where TEntity : class, new()
    {
    }
    
    0 讨论(0)
  • 2020-12-05 14:00

    This happens because of how Table<T> is declared:

    public sealed class Table<TEntity> : IQueryable<TEntity>, 
        IQueryProvider, IEnumerable<TEntity>, ITable, IQueryable, IEnumerable, 
        IListSource
    where TEntity : class  // <-- T must be a reference type!
    

    The compiler is complaining because your method has no constraints on T, which means that you could accept a T which doesn't conform to the specification of Table<T>.

    Thus, your method needs to be at least as strict about what it accepts. Try this instead:

    private static Dictionary<string, string> GetProperties<T>(Table<T> table) where T : class
    
    0 讨论(0)
  • 2020-12-05 14:05

    Just add the constraint where T : class to your method declaration.

    This is required because Table<TEntity> has a where TEntity : class constraint. Otherwise your generic method could be called with a struct type parameter, which would require the CLR to instantiate Table<TEntity> with that struct type parameter, which would violate the constraint on Table<TEntity>.

    0 讨论(0)
提交回复
热议问题