[英]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
。 UpdateState
在Child 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.