本文介绍了c#泛型错误:方法的类型参数“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);
}


推荐答案

参数到你的实现中。你不需要在你的界面上有这个限制。

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”的约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 05:22