为什么我的C#泛型方法中出现"错误:...必须是引用类型"?

Saq*_*qib 28 c# linq-to-sql

在各种数据库表中,我有一个属性和一个值列.我正在使用Linq to SQL来访问数据库.

我正在编写一个方法,它返回一个包含从给定数据库表中检索的属性/值的字典:

private static Dictionary<string, string> GetProperties<T>(Table<T> table)
{
    Dictionary<string, string> properties = new Dictionary<string, string>();

    foreach (var row in table)
    {
        properties[row.Property]=row.Value;
    }

    return properties;
}
Run Code Online (Sandbox Code Playgroud)

编译后,我得到:

Error 1 The type 'T' must be a reference type in order to use it as parameter 'TEntity' in the generic type or method 'System.Data.Linq.Table<TEntity>'

我试过没有运气的搜索这个错误信息.

搜索StackOverflow时,这个问题似乎相似,但是关于参数List:Generic List <T>作为方法的参数 - 尽管参数仍然不是该问题的答案中的引用类型.

阅读MSDN上的C#编程指南:http://msdn.microsoft.com/en-us/library/twcad0zb(VS.80).aspx我看到他们的例子都通过引用传递参数.但是,在我的特定情况下,我无法看到如何通过引用传递,因为泛型类型仅用于指定Table的泛型类型.

任何指针都将非常感激.

PS:如果我需要时间接受答案,可能会出现这种情况,因为目前无法访问此功能(我是盲人并使用屏幕阅读器).

Joh*_*lla 62

Table<T>是因为声明的方式:

public sealed class Table<TEntity> : IQueryable<TEntity>, 
    IQueryProvider, IEnumerable<TEntity>, ITable, IQueryable, IEnumerable, 
    IListSource
where TEntity : class  // <-- T must be a reference type!
Run Code Online (Sandbox Code Playgroud)

编译器抱怨,因为你的方法没有约束T,这意味着你可以接受一个T不符合规范的方法Table<T>.

因此,您的方法需要至少与它接受的内容一样严格.试试这个:

private static Dictionary<string, string> GetProperties<T>(Table<T> table) where T : class
Run Code Online (Sandbox Code Playgroud)


ito*_*son 22

只需将约束添加where T : class到方法声明中即可.

这是必需的,因为Table<TEntity>where TEntity : class约束.否则,您的泛型方法可以使用结构类型参数调用,这需要CLR Table<TEntity>使用该结构类型参数进行实例化,这将违反约束条件Table<TEntity>.