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

如何在C# WPF中从MemberInfo获取类实例?

问题解决方法

你的核心问题出在field.GetValue(member)这一行:

  • GetValue方法需要传入对象实例(此处即currentForm),而非MemberInfo元数据对象。你传入的member是成员的描述信息,不是实际的实例对象,因此返回null。

另外,GetMembers()会返回所有类型的成员(方法、属性、字段等),直接遍历会产生大量无效操作,建议直接获取字段或过滤成员类型:

修正后的代码:

public static void DefineControl(Window currentForm, Role role)
{
    // 直接获取当前窗体类型的所有实例字段(包含私有字段,窗体控件通常为私有)
    foreach (FieldInfo field in currentForm.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
    {
        AccessCategory? attribute = field.GetCustomAttribute<AccessCategory>();
        if (attribute != null)
        {
            bool authorized = attribute.Authorized(role.Categories.ToArray());
            if (!authorized)
            {
                // 传入currentForm实例,获取字段对应的控件对象
                if (field.GetValue(currentForm) is Control control)
                {
                    control.IsEnabled = false;
                }
            }
        }
    }
}

关键修改点:

  1. 用GetFields替代GetMembers,并指定绑定标志确保能获取到私有控件字段
  2. 将GetValue的参数改为currentForm,获取当前窗体实例上该字段的实际对象
  3. 用模式匹配安全转换为Control类型,避免类型转换异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 17:12:00