代码之家  ›  专栏  ›  技术社区  ›  Paul

逆变不起作用

  •  2
  • Paul  · 技术社区  · 15 年前
    public interface IMyControl<in T> where T : ICoreEntity
    {
        void SetEntity(T dataObject);
    }
    
    public class MyControl : UserControl, IMyControl<DataObject>   // DataObject implements ICoreEntity
    {
        void SetEntity(T dataObject);
    }
    

    到目前为止一切正常,但为什么会创建null?

    var control = LoadControl("~/Controls/MyControl.ascx"); // assume this line works
    IMyControl<ICoreEntity> myControl = control;
    

    1 回复  |  直到 15 年前
        1
  •  2
  •   Darin Dimitrov    15 年前

    你不能有 dataObject

    public interface ICoreEntity { }
    public class DataObject: ICoreEntity { }
    
    public interface IMyControl<out T> where T : ICoreEntity
    {
        T GetEntity();
    }
    
    public class MyControl : IMyControl<DataObject>   // DataObject implements ICoreEntity
    {
        public DataObject GetEntity()
        {
            throw new NotImplementedException();
        }
    }
    

    MyControl control = new MyControl();
    IMyControl<ICoreEntity> myControl = control;
    
    推荐文章