c#generics error:方法的类型参数'T'的约束...? [英] c# generics error: The constraints for type parameter 'T' of method ...?

查看:156
本文介绍了c#generics error:方法的类型参数'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.

class:

 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#generics error:方法的类型参数'T'的约束...?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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