[英]Passing interfaces instead of concrete classes into @ChildContent's [CascadingParameter] using <CascadingValue> in blazor
我有實現IItemContainer
的Item
和實現IItem
的ItemContainer
。
在ItemContainer.razor
我有以下內容,將自己傳遞給它的所有@ChildContent
:
<CascadingValue Value="this">
@ChildContent
</CascadingValue>
@code{
List<IItem> Items;
void AddItem(IItem item) => Items.Add(item);
.
.
.
}
在Item
class 我有以下內容:
[CascadingParameter] public IItemContainer ItemContainer {get;set;}
protected override void OnInitialized()
{
ItemContainer.AddItem(this);
}
RenderFragment RenderStuff => Do some rendering stuff with ItemContainer
.
.
.
假設我有以下內容:
<ItemContainer>
<Item>
<Item>
<Item>
</ItemContainer>
我希望當第一個<Item>
調用它的OnInitialized
時, <ItemContainer>
已經將自己傳遞給[CascadingParameter] public IItemContainer ItemContainer {get;set;}
,所以[CascadingParameter] public IItemContainer ItemContainer {get;set;}
不會是 null 和ItemContainer.AddItem(this);
將成功調用並將<Item>
添加到<ItemContainer>
的List<IItem> Items
。
如果我使用具體的類,這不是問題,即 ItemContainer 而不是 IItemContainer 的<CascadingValue Value="this">
。
但是,當<CascadingValue Value="this">
this
this 是接口而不是具體的 class 時,不會自動進行強制轉換,並且會拋出 null 異常(ItemContainer 未傳遞到級聯參數中)。
當我嘗試使用<CascadingValue TValue="IItemContainer" Value="(IItemContainer)this">
進行投射時,將引發異常。
我想將接口而不是具體類傳遞給級聯參數。 有沒有辦法使這項工作?
當我嘗試使用
<CascadingValue TValue="IItemContainer"
Value="(IItemContainer)this">
將拋出異常。
你不這樣做。 你還是要通過this
這是這樣做的方法:
<CascadingValue Value="this">
@ChildContent
</CascadingValue>
@code{
List<IItem> Items;
void AddItem(IItem item) => Items.Add(item);
.
.
.
}
@implements IItem
[CascadingParameter] public IItemContainer ItemContainer {get;set;}
protected override void OnInitialized()
{
// Note: The first ItemContainer (left to right) is the class name,
// the second is the name of the cascading parameter property. If the compiler
// fail to recognize that (I guess she won't), change this property to
// ContainerItemSet, as for instance. Otherwise, it should work perfectly
// fine.
((ItemContainer)(object)(ItemContainer)).AddItem(this);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.