c#泛型错误:方法的类型参数“T”的约束? [英] c# generics error: The constraints for type parameter 'T' of method ...?
问题描述
获取以下错误:
错误1类型参数'
T
'的方法
'genericstuff.Models.MyClass.GetCount< T>(string)
'必须匹配类型的约束
$接口方法'$ code> genericstuff.IMyClass.GetCount< T>(string)'的b $ b参数'T
'。使用显式接口实现来考虑
。
Error 1 The constraints for type parameter '
T
' of method
'genericstuff.Models.MyClass.GetCount<T>(string)
' must match the constraints for type
parameter 'T
' of interface method 'genericstuff.IMyClass.GetCount<T>(string)
'. Consider
using an explicit interface implementation instead.
类:
public class MyClass : IMyClass
{
public int GetCount<T>(string filter)
where T : class
{
NorthwindEntities db = new NorthwindEntities();
return db.CreateObjectSet<T>().Where(filter).Count();
}
}
界面:
public interface IMyClass
{
int GetCount<T>(string filter);
}
推荐答案
参数到你的实现中。你不需要在你的界面上有这个限制。
You are restricting your T generic parameter to class in your implementation. You don't have this constraint on your interface.
你需要从你的类中删除它,或者添加到你的界面,让代码编译:
You need to remove it from your class or add it to your interface to let the code compile:
由于您调用方法 CreateObjectSet< T>()
,其中需要类约束,您需要将其添加到您的界面。
Since you are calling the method CreateObjectSet<T>()
, which requires the class constraint, you need to add it to your interface.
public interface IMyClass
{
int GetCount<T>(string filter) where T : class;
}
这篇关于c#泛型错误:方法的类型参数“T”的约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!