使用 TypeDescriptor 获取私有属性
我想在 C# 中使用 TypeDescriptor 获取类的私有属性。
到目前为止,调用
TypeDescriptor.GetProperties(myType);
仅返回公共的非静态属性。
我还没有找到一种方法来影响 GetProperties 或 GetProvider 方法以强制它们返回“默认”(公共、非静态)成员之外的成员。
请不要建议反射(我很清楚 BindingFlags),除非它给了我一个 PropertyDescriptor 对象。
I would like to get private properties of the class using TypeDescriptor in c#.
So far calling
TypeDescriptor.GetProperties(myType);
returns only public, non-static properties.
I have not found a way how to influence GetProperties or GetProvider methods to force them to return other than "default" (public, non-static) members.
Please do not suggest reflection (I am well aware of BindingFlags) unless it gives me a PropertyDescriptor object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为此,您必须编写并注册一个确实使用反射的自定义
TypeDescriptionProvider
。但是,您当然可以这样做 - 您甚至可以拥有实际与字段(而不是属性)对话的PropertyDescriptor
实例。您可能还需要编写自己的定制PropertyDescriptor
实现,因为ReflectPropertyDescriptor
是内部
(您也许可以使用反射来获取它)。最终,您将必须使用反射来实现,但您可以实现TypeDescriptor.GetProperties(Type)< /code> 返回您想要的
PropertyDescriptor
实例。您也可以对您无法控制的类型执行此操作。然而,应该强调的是,你的意图是不寻常的。
如果您使用
.GetProperties(instance)
重载,那么您还可以通过实现ICustomTypeDescriptor
来实现此目的,它比完整的TypeDescriptionProvider
更简单。有关挂钩定制提供程序的示例,请参阅 HyperDescriptor
To do that you would have to write and register a custom
TypeDescriptionProvider
that does use reflection. You can certainly, however, do this - you can even havePropertyDescriptor
instances that actually talk to fields (instead of properties). You will also probably need to write your own bespkePropertyDescriptor
implementation sinceReflectPropertyDescriptor
isinternal
(you could perhaps use reflection to obtain that). Ultimately, you will have to use reflection for the implementation, but you can achieve the requirement thatTypeDescriptor.GetProperties(Type)
returnsPropertyDescriptor
instances that you want.You can do this for types outside your control, too. It should be stressed, however, that your intent is unusual.
If you were using the
.GetProperties(instance)
overload, then you can also do this by implementingICustomTypeDescriptor
which is simpler than a fullTypeDescriptionProvider
.For an example of hooking a bespoke provider, see HyperDescriptor
您可以创建自己的
CustomPropertyDescriptor
,它从PropertyInfo
获取信息。最近我需要获取非公共属性的
PropertyDescriptorCollection
。在我使用 type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic) 获取非公共属性后,我使用以下类创建相应的PropertyDescriptor。
You may create your own
CustomPropertyDescriptor
which gets the info fromPropertyInfo
.Recently I need to get the
PropertyDescriptorCollection
of nonpublic properties.After I used
type.GetProperties(BindingFlags. Instance | BindingFlags.NonPublic)
to get the nonpublic properties, then I use the following class to create the correspondingPropertyDescriptor
.