gpt4 book ai didi

c# - 如何围绕类型协方差错误进行设计

转载 作者:太空宇宙 更新时间:2023-11-03 18:47:39 25 4
gpt4 key购买 nike

如何修正这个设计。错误,因为 C# 不允许类型协变。我如何改进或更正此设计

 public interface ITimeEvent
{
}

public interface IJobTimeEvent : ITimeEvent
{
}

public interface IActivityTimeEvent : ITimeEvent
{
}

public interface IAssignmentTimeEvent<T> where T : ITimeEvent
{
T ParentTimeEvent
{
get;
set;
}
}

public class ScheduleJobTimeEvent : IAssignmentTimeEvent<IJobTimeEvent>
{
public IJobTimeEvent ParentTimeEvent
{
get;
set;
}
}

public class ScheduleActivityTimeEvent : IAssignmentTimeEvent<IActivityTimeEvent>
{
public IActivityTimeEvent ParentTimeEvent
{
get;
set;
}
}

List<IAssignmentTimeEvent<ITimeEvent>> lst = new List<IAssignmentTimeEvent<ITimeEvent>>();
lst.Add(new ScheduleJobTimeEvent()); //Error because C# doesn't allow Type Covariance
lst.Add(new ScheduleActivityTimeEvent()); //Error because C# doesn't allow Type Covariance

最佳答案

C#4.0 和 .net4.0 确实允许泛型参数(在接口(interface)上)的协变或逆变。请参阅:http://msdn.microsoft.com/en-us/library/dd799517.aspx

关于c# - 如何围绕类型协方差错误进行设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2977566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com