繁体   English   中英

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

[英]passing child Type through Lembda in Func<Parent, Parent>

我有一个这样定义的方法:

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

这可以像这样用 Parent's Child 类调用

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

编译器抱怨无法找到UpdateState UpdateStateChild class of Parent定义。 我怎样才能让chld被传递或推断为Child 我试图在chld和在不起作用的chld之后明确地说(Child)

我已经阅读了您的问题几次,虽然仍然不清楚,但我想我明白您的要求。

我假设 Child 继承自 Parent 权利?

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);
    });

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM