【问题标题】:c# generics error: The constraints for type parameter 'T' of method ...?c#泛型错误:方法的类型参数'T'的约束......?
【发布时间】:2016-10-13 21:43:17
【问题描述】:

得到以下错误:

错误 1 ​​方法类型参数“T”的约束
'genericstuff.Models.MyClass.GetCount<T>(string)' 必须匹配类型的约束
接口方法“genericstuff.IMyClass.GetCount<T>(string)”的参数“T”。考虑
改为使用显式接口实现。

类:

 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);
}

【问题讨论】:

    标签: c#-4.0 generics entity-framework-4


    【解决方案1】:

    您将 T 泛型参数限制为实现中的类。你的界面没有这个限制。

    您需要将其从您的类中移除或添加到您的界面中以让代码编译:

    由于您调用的是CreateObjectSet&lt;T&gt;() 方法,即requires the class constraint,您需要将其添加到您的界面中。

    public interface IMyClass
    {
        int GetCount<T>(string filter) where T : class;
    }
    

    【讨论】:

    • Er lopen hier best wat Nederlanders rond inderdaad! :)
    【解决方案2】:

    您要么需要将约束也应用到接口方法,要么将其从实现中删除。

    您正在通过更改实现的约束来更改接口契约 - 这是不允许的。

    public interface IMyClass
    {
        int GetCount<T>(string filter) where T : class;
    }
    

    【讨论】:

      【解决方案3】:

      你也需要限制你的界面。

      public interface IMyClass
      {
          int GetCount<T>(string filter) where T : class;
      }
      

      【讨论】:

        猜你喜欢
        • 2017-01-21
        • 1970-01-01
        • 1970-01-01
        • 2018-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-01
        相关资源
        最近更新 更多