2010-01-02 45 views
27

在各种数据库表中,我有一个属性和一个值列。我使用Linq to SQL来访问数据库。为什么在我的C#泛型方法中出现“错误:...必须是引用类型”?

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

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; 
} 

编译后,我得到:

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时,这个问题看起来很相似,尽管关于参数列表:Generic List<T> as parameter on method - 虽然该参数在该问题的答案中仍然不是引用类型。

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

任何指针将不胜感激。

PS:如果我需要时间来接受答案,因为此功能目前无法访问(我是盲人并使用屏幕阅读器)。

+0

哪条线是针对错误消息? – sblom 2010-01-02 18:56:40

+4

@Mahesh:你读过他最后一行的帖子了吗? @Saqib:您可能想要向StackOverflow的人员发出一条消息。我相信他们会想知道他们网站的一个关键功能被破坏,并且不适用于他们访问者的重要部分。 – 2010-01-02 19:01:30

+1

对不起,我没有。感谢您指出。道歉 – 2010-01-02 19:24:46

回答

59

出现这种情况是因为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! 

编译器是抱怨,因为你的方法有T没有任何限制,这意味着你可以接受T不符合的规范Table<T>

因此,您的方法至少对接受的内容至少要严格。试试这个:

private static Dictionary<string, string> GetProperties<T>(Table<T> table) where T : class 
21

只需将约束where T : class添加到您的方法声明。

这是必需的,因为Table<TEntity>有一个where TEntity : class约束。否则,可以使用struct类型参数调用泛型方法,这会要求CLR使用该结构类型参数实例化Table<TEntity>,这会违反Table<TEntity>上的约束。

0
public class TEntityRepository<TEntity> : EFRepository<TEntity> , ITEntityRepository<TEntity> 
    where TEntity : class, new() 
{ 
} 
相关问题