如何在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; } } } } }
关键修改点:
- 用
GetFields替代GetMembers,并指定绑定标志确保能获取到私有控件字段 - 将
GetValue的参数改为currentForm,获取当前窗体实例上该字段的实际对象 - 用模式匹配安全转换为
Control类型,避免类型转换异常
内容的提问来源于stack exchange,提问作者Aiorio
相关产品推荐
相关产品推荐

