实现通用接口和非通用接口

时间:2015-05-26 01:36:16

标签: c# generics

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

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:类型'字符串'不能在泛型类型或方法'ConsoleApplication1.MyClass'中用作类型参数'T'。没有从'string'到'ConsoleApplication1.INonGenericContract'的隐式引用转换。”

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

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

由于

3 个答案:

答案 0 :(得分:7)

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

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

你可能想要:

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

答案 1 :(得分:4)

你非常接近,你要做的是实现非通用接口,而不是约束。

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

答案 2 :(得分:2)

根据你的节目

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

T必须实施INonGenericContract,而string不会实施它。简而言之,string不是类MyClass

的有效参数

如果您正在寻找的是IGenericContract<T>INonGenericContract,那么您应该

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

由于where T : class已经具有该约束,因此无需IGenericContract<T>

相关问题