简体   繁体   English

C# Blazor:如何在后面的代码中使用@typeparam? (有解决方法)

[英]C# Blazor: How to use @typeparam in Code behind? (with workaround)

In a Blazor .razor file you can use @typeparam MyType to use generic parameters .在 Blazor .razor文件中,您可以使用@typeparam MyType来使用泛型参数 For example:例如:

MyComponent.razor MyComponent.razor

@typeparam MyType

<SomeHtml />

@code
{
    [Parameter]
    public List<MyType> MyList{ get; set; }
}

So you can call:所以你可以调用:

<MyComponent MyType="MyTypeABC" MyList="@MyData.MyList" />

But I prefer code behind (razor.cs), how can I use a parameter for type like @typeparam MyType in the razor.cs file?但我更喜欢后面的代码(razor.cs),我如何在 razor.cs 文件中使用像@typeparam MyType这样的类型的参数?

My current workaround is:我目前的解决方法是:

MyComponent.razor MyComponent.razor

@inherits MyComponentCode<MyType>
@typeparam MyType

MyComponent.razor.cs MyComponent.razor.cs

public class MyComponentCode<MyType> : ComponentBase
{
    [Parameter]
    public List<MyType> MyList{ get; set; }
}

I miss something like [TypeParameter] , but maybe there are better solutions, any ideas?我想念[TypeParameter]类的东西,但也许有更好的解决方案,有什么想法吗? Or maybe it's a general question about "how to use razor @statements in a code behind".或者也许这是一个关于“如何在后面的代码中使用剃刀@statements”的一般问题。


Update from 2020-02-27: 2020-02-27 更新:

With suggestion from Roger Wolf (see below), a bit better way:根据Roger Wolf 的建议(见下文),一个更好的方法:

MyComponent.razor MyComponent.razor

@typeparam MyType

MyComponent.razor.cs MyComponent.razor.cs

public partial class MyComponent<MyType>
{
    [Parameter]
    public List<MyType> MyList{ get; set; }
}

Call称呼

<MyComponent MyType="MyTypeABC" />

You were pretty close, just need to add partial to the class definition:你非常接近,只需要在类定义中添加partial

using Microsoft.AspNetCore.Components;

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

The Razor part:剃须刀部分:

@namespace BlazorApp1.Components
@typeparam T

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

The usage (Index.razor):用法(Index.razor):

@page "/"
@using BlazorApp1.Components

<MyCustomComponent T="long" Label="Custom component label" />

This way, you wouldn't need inheriting your component from it, as both become parts of the same class.这样,您就不需要从它继承您的组件,因为它们都成为同一个类的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM