本文介绍了使用TypeDescriptor获取私有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用c#中的 TypeDescriptor 获得该类的私有属性.

到目前为止致电

TypeDescriptor.GetProperties(myType);

仅返回公共的非静态属性.

我还没有找到一种方法来影响 GetProperties GetProvider 方法,以迫使它们返回默认"(公共,非静态)成员之外的其他方法./p>

请不要建议反射(我对BindingFlags非常清楚),除非它为我提供了一个 PropertyDescriptor 对象.

解决方案

要做到这一点,您将必须编写并注册一个自定义的TypeDescriptionProvider,该TypeDescriptionProvider 确实使用.但是,您当然可以这样做-您甚至可以拥有实际上与字段对话(而不是属性)的PropertyDescriptor实例.您可能还需要编写自己的定制PropertyDescriptor实现,因为ReflectPropertyDescriptorinternal(也许可以使用反射来获取).最终,您 必须使用反射进行实现,但是您可以实现TypeDescriptor.GetProperties(Type)返回您所需要的PropertyDescriptor实例的要求想要.

您也可以对超出您控制范围的类型执行此操作.但是,应该强调的是,您的意图与众不同.

如果您正在使用.GetProperties(instance)重载,那么也可以通过实现ICustomTypeDescriptor来实现,这比完整的TypeDescriptionProvider更简单.

有关挂钩定制提供程序的示例,请参见 HyperDescriptor

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.

解决方案

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 have PropertyDescriptor instances that actually talk to fields (instead of properties). You will also probably need to write your own bespke PropertyDescriptor implementation since ReflectPropertyDescriptor is internal (you could perhaps use reflection to obtain that). Ultimately, you will have to use reflection for the implementation, but you can achieve the requirement that TypeDescriptor.GetProperties(Type) returns PropertyDescriptor 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 implementing ICustomTypeDescriptor which is simpler than a full TypeDescriptionProvider.

For an example of hooking a bespoke provider, see HyperDescriptor

这篇关于使用TypeDescriptor获取私有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-09 21:57