C# Blazor:如何在代码后台中使用动态的@typeparam?

4
我想知道如何使用来自URL的@typeparam调用组件。
正如在C# Blazor: How to use @typeparam in Code behind? (with workaround)中已经讨论的那样,我像Roger Wolf在他的解决方案中所做的那样构建了一个组件。 Raozor.cs using Microsoft.AspNetCore.Components;
namespace BlazorApp1.Components
{
    public partial class MyCustomComponent<T> : ComponentBase
    {
        [Parameter]
        public string Label { get; set; }
    }
}

Razor 部分:

@namespace BlazorApp1.Components
@typeparam T
<label>@($"{Label}. Provided type is {typeof(T).Name.ToUpper()}")</label>

Index.razor页面

@page "/{typeName}"
@using BlazorApp1.Components

<MyCustomComponent T="@TypeName" Label="Custom component label" />
@code
{
    [Parameter]
    public string TypeName {get; set;}
}

因此,当我尝试通过字符串属性设置类型时,会出现编译器错误。(我猜想内部的typeof()函数将确定组件类的类型。)只有在使用固定编码的类型时才能编译。

e.g.: <MyCustomComponent T="long" Label="Custom component label" />

我想要做的是从URL中获取type参数。有什么办法可以实现这个功能吗?
1个回答

1

@typeparam 的类型在编译时被推断,你的组件应该有一个类型为 T 的参数:

namespace BlazorApp1.Components
{
    public partial class MyCustomComponent<T> : ComponentBase
    {
        [Parameter]
        public T MyParameter { get; set; }
    }
}

它用于制作通用组件,您不能将其用作示例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接