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


到目前为止一切都很好,但是为什么会创建空值呢?

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


myControl现在为空...

最佳答案

您不能将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;

关于c# - 逆差不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3378190/

10-10 22:23