为什么不能在接口上使用带有表达式的 C# 9
Why can't C# 9 with expressions be used on interfaces
我想执行以下操作(无法编译):
public ITriggerModel UpdateDirtyTrigger(ITriggerModel dirtyTriggerModel)
{
TriggerKey triggerKey = new(dirtyTriggerModel.Name, dirtyTriggerModel.Group);
ITrigger trigger = _scheduler.GetTrigger(triggerKey);
// Error: The reciever type "ITriggerModel" is not a valid record type.
return dirtyTriggerModel with
{
NextFireDateTime = trigger.GetNextFireTimeUtc(),
PreviousFireDateTime = trigger.GetPreviousFireTimeUtc(),
State = _scheduler.GetTriggerState(triggerKey),
};
}
但我设法让它工作的唯一方法是使用这种可怕的代码重复:
return dirtyTriggerModel switch
{
DailyTriggerModel daily => daily with
{
NextFireDateTime = trigger.GetNextFireTimeUtc(),
PreviousFireDateTime = trigger.GetPreviousFireTimeUtc(),
State = _scheduler.GetTriggerState(triggerKey),
},
WeeklyTriggerModel week => week with
{
NextFireDateTime = trigger.GetNextFireTimeUtc(),
PreviousFireDateTime = trigger.GetPreviousFireTimeUtc(),
State = _scheduler.GetTriggerState(triggerKey),
}
};
with 表达式适用于记录类型。
ITriggerModel
接口可以由 class 实现,UpdateDirtyTrigger
可以用 class 类型(不是记录类型)的对象调用。
我想执行以下操作(无法编译):
public ITriggerModel UpdateDirtyTrigger(ITriggerModel dirtyTriggerModel)
{
TriggerKey triggerKey = new(dirtyTriggerModel.Name, dirtyTriggerModel.Group);
ITrigger trigger = _scheduler.GetTrigger(triggerKey);
// Error: The reciever type "ITriggerModel" is not a valid record type.
return dirtyTriggerModel with
{
NextFireDateTime = trigger.GetNextFireTimeUtc(),
PreviousFireDateTime = trigger.GetPreviousFireTimeUtc(),
State = _scheduler.GetTriggerState(triggerKey),
};
}
但我设法让它工作的唯一方法是使用这种可怕的代码重复:
return dirtyTriggerModel switch
{
DailyTriggerModel daily => daily with
{
NextFireDateTime = trigger.GetNextFireTimeUtc(),
PreviousFireDateTime = trigger.GetPreviousFireTimeUtc(),
State = _scheduler.GetTriggerState(triggerKey),
},
WeeklyTriggerModel week => week with
{
NextFireDateTime = trigger.GetNextFireTimeUtc(),
PreviousFireDateTime = trigger.GetPreviousFireTimeUtc(),
State = _scheduler.GetTriggerState(triggerKey),
}
};
with 表达式适用于记录类型。
ITriggerModel
接口可以由 class 实现,UpdateDirtyTrigger
可以用 class 类型(不是记录类型)的对象调用。