Cannot convert from 'SpecificComponent' to 'ICom

本文关键字:to ICom SpecificComponent convert Cannot from | 更新日期: 2023-09-27 17:50:08

我有这样的类结构:

namespace ClassLibrary1
{
    public interface IComponentGuid { }
    class ComponentGuid : IComponentGuid{}
    internal interface IComponent<T> where T : IComponentGuid {
         List<T> List();
     }
    class SpecificComponent : IComponent<ComponentGuid> { 
      public List<ComponentGuid> List()
      {
          throw new System.NotImplementedException();
       }
    }
    class P
    {
        public P(IComponent<IComponentGuid> pComponent) { }
    }

    class Caller
    {
        public Caller()
        {
            var specific = new SpecificComponent();
            var p = new P(specific);
            }
    }
}

实例化p时出现问题:var p = new p (specific);

我得到一个
cannot convert from 'ClassLibrary1.SpecificComponent' to 'ClassLibrary1.IComponent<ClassLibrary1.IComponentGuid>'

我做错了什么?

谢谢。

Cannot convert from 'SpecificComponent' to 'ICom

你可以让它工作,如果你放弃List<T>在你的界面,并取代它与IEnumerable<T>的协变接口,然后使你的类型参数协变,以及:

namespace ClassLibrary1
{
    public interface IComponentGuid { }
    class ComponentGuid : IComponentGuid{}
    internal interface IComponent<out T> where T : IComponentGuid {
         IEnumerable<T> List();
     }
    class SpecificComponent : IComponent<ComponentGuid> { 
      public IEnumerable<ComponentGuid> List()
      {
          throw new System.NotImplementedException();
       }
    }
    class P
    {
        public P(IComponent<IComponentGuid> pComponent) { }
    }

    class Caller
    {
        public Caller()
        {
            var specific = new SpecificComponent();
            var p = new P(specific);
            }
    }
}

我正在尝试这个解决方案,将iccomponent接口分为两个,一个协变和一个不变。

namespace ClassLibrary1
{
    public interface IComponentGuid { }
    public class ComponentGuid : IComponentGuid { }
    public interface IComponentBase<out T> where T : IComponentGuid
    {
        IEnumerable<T> List();
    }
    interface IComponent<T>
    {
        void AddToList(T item );
    }
    public class SpecificComponent : IComponentBase<ComponentGuid>, IComponent<ComponentGuid>
    {
        public IEnumerable<ComponentGuid> List()
        {
            throw new System.NotImplementedException();
        }
        public void AddToList(ComponentGuid item)
        {
            throw new System.NotImplementedException();
        }
    }

    public class P
    {
        public P(IComponentBase<IComponentGuid> pComponentBase) { }
    }

    class Caller
    {
        public Caller()
        {
            var specific = new SpecificComponent();
            var p = new P(specific);
        }
    }
}