C# 对冲不是';行不通 公共接口IMyControl,其中T:icorentity { void SetEntity(T dataObject); } 公共类MyControl:UserControl,IMyControl//DataObject实现ICorentity { void SetEntity(T dataObject); }
到目前为止一切正常,但为什么会创建nullC# 对冲不是';行不通 公共接口IMyControl,其中T:icorentity { void SetEntity(T dataObject); } 公共类MyControl:UserControl,IMyControl//DataObject实现ICorentity { void SetEntity(T dataObject); },c#,asp.net,contravariance,C#,Asp.net,Contravariance,到目前为止一切正常,但为什么会创建null public interface IMyControl<in T> where T : ICoreEntity { void SetEntity(T dataObject); } public class MyControl : UserControl, IMyControl<DataObject> // DataObject implements ICoreEntity { void SetEntity(
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”);//假设这条线有效
IMyControl myControl=控制;
myControl现在为空…您不能将
数据对象
作为参数使其工作。方法只能返回它
var control = LoadControl("~/Controls/MyControl.ascx"); // assume this line works
IMyControl<ICoreEntity> myControl = control;
公共接口ICoreEntity{}
公共类数据对象:ICorentity{}
公共接口IMyControl,其中T:i重入
{
T GetEntity();
}
公共类MyControl:IMyControl//DataObject实现ICorentity
{
公共数据对象GetEntity()
{
抛出新的NotImplementedException();
}
}
现在您可以:
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 myControl=控制;
协方差不是逆变方差吗?我以为他们引入out关键字是为了让它工作?它无论如何都可以编译是的,这是协方差,但是你打算使用它的方式是协方差。看看这里:到目前为止一切都不好。这段代码甚至不编译。在第二个类中,T在哪里声明?那是不是应该是DataObject而不是T?
MyControl control = new MyControl();
IMyControl<ICoreEntity> myControl = control;