我希望使用TypeDescriptor在c#中获得该类的私有属性。
到目前为止
TypeDescriptor.GetProperties(myType);只返回公共的、非静态的属性。
我还没有找到一种方法来影响GetProperties或GetProvider方法,迫使它们返回“默认”(公共的、非静态的)成员。
请不要建议反射(我很清楚地知道PropertyDescriptor ),除非它给了我一个BindingFlags对象。
发布于 2011-10-26 09:11:54
要做到这一点,您必须编写和注册一个自定义TypeDescriptionProvider (做的),使用反射。但是,您当然可以这样做--您甚至可以拥有实际与字段(而不是属性)对话的PropertyDescriptor实例。您还可能需要编写自己的bespke PropertyDescriptor实现,因为ReflectPropertyDescriptor是internal (您也许可以使用反射来获得该实现)。最终,将不得不为实现使用反射,但您可以实现TypeDescriptor.GetProperties(Type)返回所需的PropertyDescriptor实例的要求。
您也可以对无法控制的类型执行此操作。然而,应该强调的是,你的意图是不寻常的。
如果您使用的是.GetProperties(instance)重载,那么您也可以通过实现比完整TypeDescriptionProvider更简单的ICustomTypeDescriptor来做到这一点。
有关挂钩定制提供程序的示例,请参阅HyperDescriptor
发布于 2012-10-19 10:00:02
您可以创建自己的CustomPropertyDescriptor,从PropertyInfo获取信息。
最近,我需要得到非公共属性的PropertyDescriptorCollection。
在使用type.GetProperties(BindingFlags. Instance | BindingFlags.NonPublic)获取非公共属性之后,使用下面的类创建相应的PropertyDescriptor。
class CustomPropertyDescriptor : PropertyDescriptor
{
PropertyInfo propertyInfo;
public CustomPropertyDescriptor(PropertyInfo propertyInfo)
: base(propertyInfo.Name, Array.ConvertAll(propertyInfo.GetCustomAttributes(true), o => (Attribute)o))
{
this.propertyInfo = propertyInfo;
}
public override bool CanResetValue(object component)
{
return false;
}
public override Type ComponentType
{
get
{
return this.propertyInfo.DeclaringType;
}
}
public override object GetValue(object component)
{
return this.propertyInfo.GetValue(component, null);
}
public override bool IsReadOnly
{
get
{
return !this.propertyInfo.CanWrite;
}
}
public override Type PropertyType
{
get
{
return this.propertyInfo.PropertyType;
}
}
public override void ResetValue(object component)
{
}
public override void SetValue(object component, object value)
{
this.propertyInfo.SetValue(component, value, null);
}
public override bool ShouldSerializeValue(object component)
{
return false;
}
}https://stackoverflow.com/questions/7900546
复制相似问题