假设我们有两个类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
,在其中使用相同的参数调用它。奇怪的是,这会导致以下输出:
A的性质: 可浏览属性 B的性质: 可浏览属性 不可浏览属性
为什么?