在Func <Parent,Parent>中通过Lembda传递子类型

问题描述

我有一个这样定义的方法

 public async Task<Parent> UpdateDataAsync(Func<Parent,Parent> updateExisting)
 {
   return await this.UpdateAsync<Parent>(existing => (updateExisting(existing)));
   
 }

在“父母的孩子”类中可以这样称呼

return await this.UpdateDataAsync(
            chld=>
            {
                return chld.UpdateState(State);
            });

编译器抱怨找不到UpdateStateUpdateStateChild class of Parent上定义。如何使chld被传递或推断为Child。我试图在(Child)的前面和在无效的lembda之后明确说出chld

解决方法

我已经读过几次您的问题了,虽然还不清楚,但是我想我能理解您的要求。

我认为孩子是从父母那里继承的吗?

public class Parent
{
}

public class Child : Parent
{
   public Child UpdateState(State state)
   {
        //whatever this does
        return this;
   }
}

如果我是正确的,请使用此信息更新您的问题。

因此,假设上述正确无误,则需要使您的UpdateDataAsync方法具有约束通用性

public async Task<TParent> UpdateDataAsync<TParent>(Func<TParent,TParent> updateExisting)
where TParent : Parent
{
   return await this.UpdateAsync<TParent>(existing => (updateExisting(existing)));   
}

这允许C#在允许您使用子类的同时知道该项目是父项。

这意味着您可以执行此操作

return await this.UpdateDataAsync<Child>(
    chld=>
    {
        return chld.UpdateState(State);
    });

注意这里的type参数可能是不需要的,因为编译器可以推断出它,但是为了清楚起见,我已经包含了它