本文介绍了C#Blazor:如何在后面的代码中使用@typeparam? (有解决方法)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Blazor .razor 文件中,您可以使用@typeparam MyType使用通用参数.例如:

In a Blazor .razor file you can use @typeparam MyType to use generic parameters.For example:

MyComponent.razor

@typeparam MyType

<SomeHtml />

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

因此您可以致电:

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

但是我更喜欢(razor.cs)后面的代码,如何在razor.cs文件中使用像@typeparam MyType这样的类型的参数?

But I prefer code behind (razor.cs), how can I use a parameter for type like @typeparam MyType in the razor.cs file?

我当前的解决方法是:

MyComponent.razor

@inherits MyComponentCode<MyType>
@typeparam MyType

MyComponent.razor.cs

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

我想念[TypeParameter]之类的东西,但是也许有更好的解决方案,有什么想法吗?也许这是关于如何在后面的代码中使用razor @statements"的一般问题.

I miss something like [TypeParameter], but maybe there are better solutions, any ideas? Or maybe it's a general question about "how to use razor @statements in a code behind".

从2020-02-27更新:

Update from 2020-02-27:

罗杰·沃尔夫(见下文)的建议下,一种更好的方法:

With suggestion from Roger Wolf (see below), a bit better way:

MyComponent.razor

@typeparam MyType

MyComponent.razor.cs

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

致电

<MyComponent MyType="MyTypeABC" />

推荐答案

您非常接近,只需在类定义中添加partial:

You were pretty close, just need to add partial to the class definition:

using 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):

The usage (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.

这篇关于C#Blazor:如何在后面的代码中使用@typeparam? (有解决方法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 02:35