1

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

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,在其中使用相同的参数调用它。奇怪的是,这会导致以下输出:

A的性质:
可浏览属性

B的性质:
可浏览属性
不可浏览属性

为什么?

4

0 回答 0