[英]How Blazor infer the data type of @typeparam directive?
The code below was made using.Net 5.0.203下面的代码是使用.Net 5.0.203 制作的
I've this component我有这个组件
MyComponent.razor MyComponent.razor
@typeparam TItem
<p>MyComponent: @typeName</p>
@code {
[Parameter]
public IEnumerable<TItem> Data { get; set; }
string typeName;
protected override void OnInitialized()
{
typeName = typeof(TItem).Name;
}
}
and here is the page calling the component这是调用组件的页面
Index.razor索引.razor
@page "/"
<MyComponent Data="@items"></MyComponent>
<p>Page: @itemsType</p>
@code
{
string[] items = new string[2];
string itemsType;
protected override void OnInitialized()
{
itemsType = items.GetType().Name;
}
}
I expected the type of TItem in MyComponent is String[] however it's String我预计MyComponent中TItem的类型是String[]但它是String
How Blazor infer the type of TItem? Blazor如何推断TItem的类型?
When you use the generic constraint of typeparam TItem
is says when you create the component you must specify what that type is.当您使用
typeparam TItem
的通用约束时,当您创建组件时,您必须指定该类型是什么。
When you called your component here:当你在这里调用你的组件时:
<MyComponent Data="@items"></MyComponent>
You passed the @items
object as the parameter.您将
@items
object 作为参数传递。
If you don't explicitly tell the component what type it should expect, it will by default use whatever type is passed to it.如果你没有明确地告诉组件它应该期望什么类型,默认情况下它会使用传递给它的任何类型。
You passed it a string[]
so it said "He gave me a string[]
so i'm going to assume the TItem
is of type string
".你给它传递了一个
string[]
,所以它说“他给了我一个string[]
,所以我假设TItem
的类型是string
”。 It does this because string[]
is implicitly convertible to IEnumerable<TItem>
since TItem
can be any object unless you constrain that parameter.这样做是因为
string[]
可以隐式转换为IEnumerable<TItem>
因为TItem
可以是任何 object ,除非您限制该参数。 so it can only be certain types所以它只能是某些类型
Another thing of note is that TItem
is the type of the object that is contained within the IEnumerable<TItem>
parameter.另一件值得注意的事情是
TItem
是IEnumerable<TItem>
参数中包含的 object 的类型。 If you want to check to see what type of IEnumerable
that was passed instead maybe do something like:如果您想查看传递的
IEnumerable
类型,则可以执行以下操作:
string[] s = new string[] { "fox" };
Check(s);
static void Check<T>(IEnumerable<T> maybeArray)
{
Console.WriteLine(typeof(T)); // System.String
Console.WriteLine(maybeArray is T[]); // true
Console.WriteLine(maybeArray is List<T>); // false
}
If you want TItem
to be a string[]
consider instead accepting TItem
as a parameter instead of IEnumerable<TItem>
.如果您希望
TItem
成为string[]
,请考虑接受TItem
作为参数而不是IEnumerable<TItem>
。
Such as:如:
[Parameter]
public TItem Data { get; set; }
Make sure to include a constraint on TItem
if you need it to be enumerable.如果您需要它是可枚举的,请确保在
TItem
上包含一个约束。
For more information on how to include a generic constraint in blazor (it's weird) check out this post )有关如何在 blazor 中包含通用约束的更多信息(这很奇怪),请查看这篇文章)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.