【问题标题】:Implementing a Generic Interface and a Non Generic Interface实现通用接口和非通用接口
【发布时间】:2015-05-26 01:36:16
【问题描述】:

我有两个合同(一个通用接口和另一个非通用)如下:

public interface IGenericContract<T>  where T : class
    {
        IQueryable<T> GetAll();
    }

public interface INonGenericContract
    {
        string GetFullName(Guid guid);
    }

我有一个实现两者的类

public class MyClass<T> :
        IGenericContract<T> where T : class, INonGenericContract
    {
        public IQueryable<T> GetAll()
        {
            ...
        }

        public string GetFullName(Guid guid)
        {
            ...
        }
    }

一切都很好,直到我编译它。 但是现在当我尝试使用这个类时,我遇到了这个错误 “错误 CS0311:类型 'string' 不能用作泛型类型或方法 'ConsoleApplication1.MyClass' 中的类型参数 'T'。没有从 'string' 到 'ConsoleApplication1.INonGenericContract' 的隐式引用转换。”

class Program
    {
        static void Main(string[] args)
        {
            MyClass<string> myClass = new MyClass<string>(); //Error
        }
    }

如果我不实施非通用合同,它可以正常工作。这里有什么问题?

谢谢

【问题讨论】:

    标签: c# generics


    【解决方案1】:

    在您的代码中,INonGenericContract 是通用约束的一部分,因为它放在 where 之后。

    public class MyClass<T> :
        IGenericContract<T> where T : class, INonGenericContract
    

    你可能想要这样:

    public class MyClass<T> :
        IGenericContract<T>, INonGenericContract where T : class
    

    【讨论】:

      【解决方案2】:

      你很接近,你要做的是实现非泛型接口,而不是施加约束。

      public class MyClass<T> :
          IGenericContract<T>, INonGenericContract where T : class
      {
          public IQueryable<T> GetAll()
          {
              return null;
          }
      
          public string GetFullName(Guid guid)
          {
              return null;
          }
      }
      

      现在你可以这样做了

      MyClass<string> myClass = new MyClass<string>(); 
      

      【讨论】:

        【解决方案3】:

        根据您显示的内容

        public class MyClass<T> : IGenericContract<T> where T : class, INonGenericContract
        

        T 必须实现 INonGenericContractstring 没有实现它。简而言之,string 不是类MyClass 的有效参数

        如果您正在寻找的是实现IGenericContract&lt;T&gt;INonGenericContract,您应该有

        public class MyClass<T> : INonGenericContract, IGenericContract<T>
        

        没有必要有where T : class,因为IGenericContract&lt;T&gt; 已经有了这个约束。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-06-20
          • 1970-01-01
          相关资源
          最近更新 更多