[英]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.