如何自动获取C# List中对象类型?Blazor组件问题
解决Blazor Server组件自动获取List元素类型属性的问题
你之前写的typeof(people.GetType)是语法错误:typeof仅能接收类型名称,而people.GetType()是实例方法调用,返回的是Type对象。另外,即使修正写法,也不能在字段初始化阶段使用——因为字段初始化逻辑早于组件的OnInitialized,如果后续people是通过组件参数传入而非硬编码初始化,此时people可能还未赋值,导致获取不到正确类型。
以下是两种解决方案:
快速修复当前代码(保持固定Person类型)
修改.cs文件,将属性信息的获取逻辑移到OnInitialized中:
// 先声明字段,不提前初始化 private PropertyInfo[] properties; private List<Person> people = new List<Person>(); private List<string> columns; private string database = "Name'Address'Region'Country"; protected override void OnInitialized() { base.OnInitialized(); columns = database.Split("'").ToList(); // 方式1:通过列表第一个元素获取类型(需确保列表非空) if (people.Any()) { properties = people.First().GetType().GetProperties(); } // 方式2:直接获取List泛型参数的类型(即使列表为空也能生效) // var itemType = typeof(List<Person>).GetGenericArguments()[0]; // properties = itemType.GetProperties(); people.Add(new Person { Name = "John Doe", Address = "Somewhere 111", City = "Somewhere", Region = "Elsewhere", PostalCode = "11153AA", Country = "Earth" }); }
更通用的泛型组件方案
将组件改为泛型结构,支持任意类型的对象列表复用:
.cs文件
using System.Reflection; using Microsoft.AspNetCore.Components; public partial class GenericTable<T> where T : class { // 通过组件参数接收列表数据 [Parameter] public List<T> Items { get; set; } = new List<T>(); // 通过参数接收列配置 [Parameter] public string ColumnConfig { get; set; } = "Name'Address'Region'Country"; private PropertyInfo[] properties; private List<string> columns; protected override void OnInitialized() { base.OnInitialized(); columns = ColumnConfig.Split("'").ToList(); // 直接获取泛型参数T的属性,无需依赖列表实例 properties = typeof(T).GetProperties(); } }
.razor文件
<table> <thead> <tr> @foreach (var prop in properties) { if (columns.Contains(prop.Name)) { <th>@prop.Name</th> } } </tr> </thead> <tbody> @foreach (var item in Items) { <tr> @foreach (var prop in properties) { if (columns.Contains(prop.Name)) { <td>@prop.GetValue(item)</td> } } </tr> } </tbody> </table>
调用泛型组件
在父组件中指定泛型类型并传入数据:
<GenericTable T="Person" Items="@people" ColumnConfig="Name'Address'Region'Country" />
内容的提问来源于stack exchange,提问作者Jeremy
相关产品推荐
相关产品推荐

