【问题标题】:C# Interface Error: There is no implicit reference conversion from class xxx to interface xxxxC#接口错误:没有从类xxx到接口xxxx的隐式引用转换
【发布时间】:2014-02-10 09:23:18
【问题描述】:

我在不同的命名空间下有以下类。我的意思是,相同的 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; }
}

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

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

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

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

编译时出现以下错误

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>'.

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

【问题讨论】:

    标签: c# .net generics interface implicit-conversion


    【解决方案1】:
    public interface iC<T, TI> 
        where T : iB<TI> 
        where TI : iA
    {
       List<T> listBinC {get; set; }
    }
    

    这里iA作为一个单独的泛型参数被拉出,所以你可以对其应用一个约束(TIiA派生)然后像这样声明B

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

    【讨论】:

    • 从第一个角度理解有点棘手,但经过几分钟的思考,它解决了我的问题。谢谢
    猜你喜欢
    • 2012-12-01
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多