假设我们有两个类A
和B
。类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
为什么?