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

如何从Fody CustomAttribute构造函数获取命名值?

在Fody中读取CustomAttribute的命名参数值

你遇到的问题核心是混淆了构造函数位置参数和**命名参数(属性赋值)**的存储位置:

  • ConstructorArguments仅存储传递给属性构造函数的位置参数,比如[Display("直接传的构造参数")]这种形式的值会在这里。
  • 像[Display(Name = "This name and value")]里的Name赋值属于命名参数,需要从CustomAttribute的NamedArguments集合中读取,而不是Properties(这个字段在Fody API里并非用于这类场景)。

具体实现代码

遍历NamedArguments集合,匹配成员名即可获取对应值:

var displayAttribute = // 从目标成员/类型上获取到的DisplayAttribute实例
foreach (var namedArg in displayAttribute.NamedArguments)
{
    if (namedArg.MemberName == "Name")
    {
        string nameValue = namedArg.TypedValue.Value.ToString();
        // 这里就是你要的Name属性值
    }
}

额外注意事项

  • 确认你获取的CustomAttribute确实是目标元素上的那个DisplayAttribute,避免误取其他属性。
  • 不同版本的Fody API可能有细节差异,但NamedArguments是处理这类命名参数的标准入口。

内容的提问来源于stack exchange,提问作者Peter Morris

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 04:30:00