简体   繁体   English

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

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

I have a method defined like this:我有一个这样定义的方法:

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

This can be called like this with Parent's Child class这可以像这样用 Parent's Child 类调用

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

Compiler complains about not being able to find UpdateState .编译器抱怨无法找到UpdateState UpdateState is defined on Child class of Parent . UpdateStateChild class of Parent定义。 How can I make chld to be passed or inferred as Child .我怎样才能让chld被传递或推断为Child I tried to explicitly say (Child) infront of chld and after the lembda that doesnt work.我试图在chld和在不起作用的chld之后明确地说(Child)

I've read your question a couple of times and while its still not clear, I think I get what your asking.我已经阅读了您的问题几次,虽然仍然不清楚,但我想我明白您的要求。

I assume that Child inherits from Parent right?我假设 Child 继承自 Parent 权利?

public class Parent
{
}

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

If I'm correct please update your question with this information.如果我是正确的,请使用此信息更新您的问题。

So assuming the above is correct you need to make your UpdateDataAsync method generic with a constraint因此,假设上述内容是正确的,您需要使用约束使 UpdateDataAsync 方法通用

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

This allows C# to know that the item is a Parent while allowing you to work with a subclass这允许 C# 知道该项目是父项,同时允许您使用子类

which means you can then do this这意味着你可以这样做

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

NB the type parameter here is probably unneeded, since the compiler can infer it, but I've included it for clarity注意这里的类型参数可能是不需要的,因为编译器可以推断它,但为了清楚起见,我已经包含了它

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

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