问题描述
在各种数据库表中,我有一个属性列和一个值列.我正在使用 Linq to SQL 访问数据库.
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 containing the properties/values retrieved from the given database table:
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; }
编译后,我得到:
错误 1 ??类型T"必须是引用类型,才能将其用作泛型类型或方法System.Data.Linq.Table
我尝试搜索此错误消息,但没有成功.
I've tried searching for this error message without luck.
搜索 StackOverflow,这个问题似乎很相似,但关于参数列表:Generic List<>作为方法的参数 - 尽管该参数在该问题的答案中仍然不是引用类型.
Searching StackOverflow, this question seems similar, though regarding a parameter List: Generic List<T> as parameter on method - though the parameter still isn't a reference type in the answers to that question, either.
阅读 MSDN 上的 C# 编程指南:http://www.51sjk.com/Upload/Articles/1/0/339/339376_20221213104032844.aspx 我看他们的例子都是通过引用传递参数的.但是,在我的特定情况下,我看不到如何通过引用传递,因为泛型类型仅用于指定 Table 的泛型类型.
Reading the C# Programming Guide on MSDN: http://www.51sjk.com/Upload/Articles/1/0/339/339376_20221213104032844.aspx I see their examples all pass the parameters by reference. However, I can't see how to pass by reference in my particular case, since the generic type is just for specifying the generic type of Table.
任何指针将不胜感激.
PS:抱歉,如果我需要时间来接受答案,因为此功能目前无法使用(我是盲人,使用屏幕阅读器).
PS: Appologies if it takes time for me to accept an answer, as this feature is currently not accessible (I'm blind and use a screen reader).
推荐答案
发生这种情况的原因是 Table
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!
编译器抱怨,因为你的方法对T没有约束,这意味着你可以接受一个不符合规范的T表
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