【问题标题】:C# Blazor: How to use a dynamic @typeparam in Code behind?C# Blazor:如何在 Code behind 中使用动态 @typeparam?
【发布时间】:2020-07-08 22:23:58
【问题描述】:

我想知道,如何使用来自 URL 的 @typeparam 调用组件

正如 C# Blazor: How to use @typeparam in Code behind? (with workaround) 中已经讨论过的那样,我构建了一个组件,就像 Roger Wolf 在他的解决方案中所做的那样。

Raozor.cs 使用 Microsoft.AspNetCore.Components;

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

剃刀部分:

@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 中提取类型参数。有什么想法可以完成这项工作吗?

【问题讨论】:

    标签: asp.net-core blazor


    【解决方案1】:

    @typeparam 的类型是在编译时推导出来的,您的组件中应该有一个T 类型的参数:

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

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

    【讨论】:

      猜你喜欢
      • 2021-05-17
      • 1970-01-01
      • 2020-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多