无法使用反射访问受保护的属性

问题描述

在断点调试时,我无法使用反射在观察窗口中看到的属性Rectangle_1(和其他同级属性)进行访问。

watch window

在立即窗口中,如果我尝试

typeof(LoadRecipeSlots).GetProperty("Rectangle_1")

结果是null

但如果我尝试

typeof(LoadRecipeSlots).GetProperty("Visible")

结果是

{Boolean Visible}
Attributes: None
CanRead: true
CanWrite: true
CustomAttributes: Count = 1
DeclaringType: DeclaredProperties = {System.Reflection.PropertyInfo[65]}
GetMethod: {Boolean get_Visible()}
IsSpecialName: false
MemberType: Property
MetadataToken: 385877353
Module: {ControlsCF.dll}
Name: "Visible"
PropertyType: DeclaredProperties = {System.Reflection.PropertyInfo[0]}
ReflectedType: DeclaredProperties = {System.Reflection.PropertyInfo[7]}
SetMethod: {Void set_Visible(Boolean)}

属性Visible似乎是父类的属性。

Rectangle_1中的属性LoadRecipeSlotsfrom tensorflow.keras.metrics import Recall,Precision,Metric 的保护,我试图使用Reflection从局部类定义中访问它,这是我做不到的。但是,可以在此部分类定义中将该属性作为代码访问。

大多数代码是由使用中的工具iX Developer自动生成的,因此我无法创建一个简洁的示例。如果缺少某些内容,请告诉我,我会尝试将其添加到问题中。

解决方法

typeof(LoadRecipeSlots).GetProperty("Rectangle_1")

将仅搜索公共属性。由于您的财产受到保护,因此您需要指定还应搜索非公共财产:

typeof(LoadRecipeSlots).GetProperty("Rectangle_1",BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
,

这是因为您要访问的属性是受保护的(不是公共的),默认情况下GetProperty(String)仅返回公共属性。

您可以像下面那样使用GetProperty(String,BindingFlags)来检索您的受保护财产:

typeof(LoadRecipeSlots).GetProperty("Rectangle_1",BindingFlags.NonPublic)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...