为什么我会和QUOT;错误:...必须是引用类型"在我的C#泛型方法? [英] Why do I get "error: ... must be a reference type" in my C# generic method?

查看:99
本文介绍了为什么我会和QUOT;错误:...必须是引用类型"在我的C#泛型方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在各种数据库中的表我都一个属性和一个值列。我使用LINQ到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;
}



一旦编译,我得到:

Upon compiling, I get:

错误1型'T'必须是引用类型,才能在泛型类型或方法使用它作为参数'TEntitySystem.Data这.Linq.Table< TEntity>

我试过没有运气搜索此错误消息。

I've tried searching for this error message without luck.

搜索计算器,这个问题似乎大同小异,但对于一个参数列表:的 http://stackoverflow.com/questions/1633690/generic-listt-as-parameter-on-method - 尽管参数仍然不在答案引用类型。对这个问题,无论是

Searching StackOverflow, this question seems similar, though regarding a parameter List: http://stackoverflow.com/questions/1633690/generic-listt-as-parameter-on-method - though the parameter still isn't a reference type in the answers to that question, either.

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

Reading the C# Programming Guide on MSDN: http://msdn.microsoft.com/en-us/library/twcad0zb(VS.80).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:如果Appologies需要时间,我接受一个答案,因为这个功能目前无法访问的(我是盲人和使用屏幕阅读器)

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).

推荐答案

这是因为如何表< 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 这不符合表1所述的规范; 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

这篇关于为什么我会和QUOT;错误:...必须是引用类型&QUOT;在我的C#泛型方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆