按属性实例过滤的TypeDescriptor.GetProperties无法与实现ICustomTypeDescriptor

时间:2017-11-01 09:50:26

标签: .net typedescriptor getproperties icustomtypedescriptor

假设我们有两个类AB。类A具有一些可浏览和不可浏览的属性,类B派生自A并实现ICustomTypeDescriptor接口(仅通过调用TypeDescriptor方法true传递为noCustomTypeDesc参数)。这是代码:

public class A
{
  public int BrowsableProperty { get; set; }

  [Browsable(false)]
  public int NonBrowsableProperty { get; set; }
}

public class B : A, ICustomTypeDescriptor
{
  public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
  public string GetClassName() => TypeDescriptor.GetClassName(this, true);
  public string GetComponentName() => TypeDescriptor.GetComponentName(this, true);
  public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
  public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
  public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
  public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
  public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
  public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
  public PropertyDescriptorCollection GetProperties() => TypeDescriptor.GetProperties(this, true);
  public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => TypeDescriptor.GetProperties(this, attributes, true);
  public object GetPropertyOwner(PropertyDescriptor pd) => this;
}

现在让我们看看TypeDescriptor.GetProperties为这些类的实例返回的内容:

var a = new A();
var b = new B();
var browsable = new Attribute[] { BrowsableAttribute.Yes };

Console.WriteLine("Properties of A:");
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(a, browsable, true))
  Console.WriteLine(property.Name);
Console.WriteLine();

Console.WriteLine("Properties of B:");
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(b, browsable, true))
  Console.WriteLine(property.Name);

请注意noCustomTypeDesc = true是有意的。这只是在ICustomTypeDescriptor实现中的示例,它使用相同的参数调用它。奇怪的是,这导致以下输出:

Properties of A:
BrowsableProperty

Properties of B:
BrowsableProperty
NonBrowsableProperty

为什么?

0 个答案:

没有答案