You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# MVC:通用Razor视图中通过反射获取带ResourceType的Display特性值

解决方法:通过反射获取带ResourceType的Display特性值

我来帮你搞定这个需求!当你的DisplayAttribute指定了ResourceType参数时,直接读取Name属性拿到的只是资源文件里的键,想要获取实际的本地化文本,得通过资源类来读取。下面是适配你Razor视图场景的具体实现:

首先,我们需要在遍历属性的过程中,完成以下几步:

  • 获取属性上的DisplayAttribute实例
  • 判断是否指定了ResourceType,如果是则从资源类中读取对应键的值
  • 处理没有DisplayAttribute或者资源键不存在的兜底情况

完整Razor代码示例

@using System.Reflection
@using System.Resources

@model IEnumerable<IFirstLevetOverviewModel>

<table>
    <thead>
        <tr>
            @foreach (var prop in Model.FirstOrDefault()?.GetType().GetProperties() ?? Enumerable.Empty<PropertyInfo>())
            {
                var displayAttr = prop.GetCustomAttribute<DisplayAttribute>();
                string columnHeader;

                if (displayAttr != null)
                {
                    if (displayAttr.ResourceType != null)
                    {
                        // 方式1:使用ResourceManager读取资源值(通用兼容所有资源类)
                        var resourceManager = new ResourceManager(displayAttr.ResourceType);
                        columnHeader = resourceManager.GetString(displayAttr.Name) 
                                      ?? displayAttr.Name 
                                      ?? prop.Name;

                        // 方式2:强类型资源类可直接反射读取静态属性(性能略优)
                        // var resourceProperty = displayAttr.ResourceType.GetProperty(
                        //     displayAttr.Name, 
                        //     BindingFlags.Public | BindingFlags.Static);
                        // columnHeader = resourceProperty?.GetValue(null) as string 
                        //               ?? displayAttr.Name 
                        //               ?? prop.Name;
                    }
                    else
                    {
                        // 未指定资源类,直接使用Display特性的Name或属性名
                        columnHeader = displayAttr.Name ?? prop.Name;
                    }
                }
                else
                {
                    // 无Display特性,直接用属性名
                    columnHeader = prop.Name;
                }

                <th>@columnHeader</th>
            }
        </tr>
    </thead>
    <tbody>
        <!-- 表格行内容渲染逻辑 -->
    </tbody>
</table>

关键细节说明

  1. 空值安全处理:用Model.FirstOrDefault()?.GetType().GetProperties() ?? Enumerable.Empty<PropertyInfo>()避免集合为空时出现空引用异常
  2. 资源读取兜底:如果资源键不存在,会依次降级使用DisplayAttribute.Name、属性名作为备用文本
  3. 两种资源读取方式:
    • ResourceManager方式:无需关心资源类是否是强类型,通用性更强
    • 反射静态属性方式:适合强类型资源类(比如Visual Studio自动生成的资源类),调用更直接

内容的提问来源于stack exchange,提问作者Roman Borovets

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:15:21