C#接口错误:没有从类xxx到接口xxxx的隐式引用转换

时间:2021-10-30 21:20:22

I have following classes under different namespaces. I mean, the same 3 classes exist under different namespaces.

我在不同的命名空间下面有以下类。我的意思是,在不同的命名空间下存在相同的3个类。

public class A
{
   public int a { get; set; }
}

public class B
{
   public A objA { get; set; }
}

public class C
{
   public List<B> listBinC { get; set; }
}

In order to utilize/operate between the objects of these classes I thought of writing an interface wrapper such as

为了在这些类的对象之间利用/操作,我想到编写一个接口包装器,如

public interface iA
{
   int a { get; set; }
}

public interface iB<T> where T: iA
{
   T objA { get; set; }
}

public interface iC<T> where T : iB<iA>
{
   List<T> listBinC {get; set; }
}

After this I have changed my Class definitions to

在此之后,我将我的类定义更改为

public class A : iA
{
    public int a { get; set; }
}

public class B : iB<A>
{
    public A objA { get; set; }
}

class C : iC<B>
{
    public List<B> listBinC { get; set; }
}

When Compiled I am getting the following Error

编译时我收到以下错误

The type 'Example.B' cannot be used as type parameter 'T' in the generic type or method 'Example.iC<T>'. 
There is no implicit reference conversion from 'Example.B' to 'Example.iB<Example.iA>'.

I cannot change my class structure as it is provided by different team. What is the right way to enforce the interface 'constraints' to resolve the error?

我不能改变我的班级结构,因为它是由不同的团队提供的。强制执行界面“约束”以解决错误的正确方法是什么?

1 个解决方案

#1


3  

public interface iC<T, TI> 
    where T : iB<TI> 
    where TI : iA
{
   List<T> listBinC {get; set; }
}

Here iA is pulled out as a separate generic parameter, so you can apply a constraint on it (for TI to be derived from iA) and then declare B like this:

这里iA被拉出作为一个单独的通用参数,因此你可以对它应用约束(TI从iA派生)然后像这样声明B:

class C : iC<B, A>
{
    public List<B> listBinC { get; set; }
}

#1


3  

public interface iC<T, TI> 
    where T : iB<TI> 
    where TI : iA
{
   List<T> listBinC {get; set; }
}

Here iA is pulled out as a separate generic parameter, so you can apply a constraint on it (for TI to be derived from iA) and then declare B like this:

这里iA被拉出作为一个单独的通用参数,因此你可以对它应用约束(TI从iA派生)然后像这样声明B:

class C : iC<B, A>
{
    public List<B> listBinC { get; set; }
}