gpt4 book ai didi

c# - 行动 lambda 中的逆变 - C#

转载 作者:太空狗 更新时间:2023-10-29 22:55:09 27 4
gpt4 key购买 nike

我有这样的类层次结构

public abstract class CalendarEventBase{}

public class TrainingEvent : CalendarEventBase{}

public class AuditEvent : CalendarEventBase{}

我想创建一个 Action Action lamda,它有一个 CalendarEventBase 类型的通用类型参数,我可以将其分配给以下不同的方法:

public void EmailCancelation(TrainingEvent trainingEvent)

public void EmailCancelation(AuditEvent auditEvent)

我创建了以下非法分配:

Action<CalendarEventBase> emailCancelation = _trainingService.EmailTrainingCancellation;

编译器提示它期待一个带有 void(CalendarEventBase) 作为签名的方法。我对此感到惊讶,因为我认为它会接受更派生的类型。

为了解决这个问题,我创建了以下允许我完成任务的委托(delegate):

public delegate void EmailCancelation<in T>(T calendarEvent) where T : CalendarEventBase;

我的问题是,我是否可以在不创建额外委托(delegate)的情况下完成任务?我以为我可以创建一个 Action 实例。

任何帮助或指点,非常感谢。

最佳答案

行:

Action<CalendarEventBase> emailCancelation = _trainingService.EmailTrainingCancellation;

实际上期望协变,而不是逆变。但这在逻辑上没有意义;该方法需要一个 TrainingEvent 作为输入 - 如何将一个更通用类型 (CalendarEventBase) 传递给它?

这是不合法的:

// What if the method wants to make the lion roar but you pass in a goat?
Action<Mammal> mammalAction = MethodThatTakesALion;

但这很好:

// Anything that you want to with an animal, you can do with a mammal.
Action<Mammal> mammalAction = MethodThatTakesAnAnimal;

关于c# - 行动 lambda 中的逆变 - C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4968535/

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