【发布时间】:2011-10-24 07:49:20
【问题描述】:
我有一个这样声明的扩展方法:
public static IEnumerable<TEntity> AsEnumerable<TEntity>(this IDBQueryable<TEntity> dbQueryable) where TEntity : class
{
return dbQueryable.Query.AsEnumerable();
}
下一个是使用示例:
//It works properly
IDBQueryable<Customer> customers = GetCustomerSet();
customers.AsEnumerable();
// It cannot be compiled because int type doesn't fullfill
// the constrains of the extension method
// It must be a reference type in order to be passed as a parammeter.
IDBQueryable<int> customerIDs = GetCustomerIDs();
customers.AsEnumerable();
我怎样才能有一个适用于我展示的两个用例的扩展方法? 提前谢谢你。
【问题讨论】:
-
@Eric
Int32在 .NET 中与int相同;没有拳击(它只是一个语言级别的别名;int===global::System.Int32) -
如果您删除了对扩展方法的约束,是否会出现编译错误?
-
@Eric 重点是我的 POCO Id 是用 Id 定义的,这不是我可以更改的。
-
@Nick 是的,我收到此错误类型“TEntity”必须是引用类型才能将其用作泛型类型或方法“
”中的参数“TEntity” -
您在上一条评论中遗漏了重要的一点:...在泛型类型或方法中 '[important bit]
'
标签: c# generics extension-methods constraints