逆变法不起作用

时间:2010-07-31 13:00:12

标签: c# asp.net contravariance

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;

myControl现在为空......

1 个答案:

答案 0 :(得分:2)

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