2010-01-02 46 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() 
{ 
} 
相關問題