在 Blazor .razor文件中,您可以@typeparam MyType
使用泛型参数。例如:
MyComponent.razor
@typeparam MyType
<SomeHtml />
@code
{
[Parameter]
public List<MyType> MyList{ get; set; }
}
Run Code Online (Sandbox Code Playgroud)
所以你可以调用:
<MyComponent MyType="MyTypeABC" MyList="@MyData.MyList" />
Run Code Online (Sandbox Code Playgroud)
但我更喜欢后面的代码(razor.cs),我如何使用像@typeparam MyType
razor.cs 文件中的类型的参数?
我目前的解决方法是:
MyComponent.razor
@inherits MyComponentCode<MyType>
@typeparam MyType
Run Code Online (Sandbox Code Playgroud)
MyComponent.razor.cs
public class MyComponentCode<MyType> : ComponentBase
{
[Parameter]
public List<MyType> MyList{ get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我想念类似的东西[TypeParameter]
,但也许有更好的解决方案,有什么想法吗?或者也许这是一个关于“如何在后面的代码中使用剃刀@statements”的一般问题。
2020-02-27 更新:
根据Roger Wolf 的建议(见下文),一个更好的方法:
MyComponent.razor
@typeparam MyType
Run Code Online (Sandbox Code Playgroud)
MyComponent.razor.cs
public partial class MyComponent<MyType>
{
[Parameter]
public List<MyType> MyList{ get; set; }
}
Run Code Online (Sandbox Code Playgroud)
称呼
<MyComponent MyType="MyTypeABC" />
Run Code Online (Sandbox Code Playgroud)
Rog*_*olf 15
您非常接近,只需要添加partial
到类定义中:
using Microsoft.AspNetCore.Components;
namespace BlazorApp1.Components
{
public partial class MyCustomComponent<T> : ComponentBase
{
[Parameter]
public string Label { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
剃须刀部分:
@namespace BlazorApp1.Components
@typeparam T
<label>@($"{Label}. Provided type is {typeof(T).Name.ToUpper()}")</label>
Run Code Online (Sandbox Code Playgroud)
用法(Index.razor):
@page "/"
@using BlazorApp1.Components
<MyCustomComponent T="long" Label="Custom component label" />
Run Code Online (Sandbox Code Playgroud)
这样,您就不需要从它继承您的组件,因为它们都成为同一个类的一部分。