我意识到这是一个不寻常的问题,但是:
我已经创建了一个自定义TypeDescriptionProvider,它可以根据请求的对象类型存储和返回不同的TypeDescriptors。然而,我注意到的是,无论与类型关联的TypeDescriptionProvider (可以是自定义的,还是默认的),TypeDescriptor.GetProvider()总是返回一个(内部类) System.ComponentModel.TypeDescriptor.TypeDescriptionNode对象(实际TypeDescriptionProvider的某种包装器)。反过来,在这个对象上调用GetTypeDescriptor()总是返回一个System.ComponentModel.TypeDescriptor.TypeDescriptionNode.DefaultTypeDescriptor对象(另一个包装器),陌生人仍然不会调用TypeDescriptionProvider的实际GetTypeDescriptor()方法。
这是否意味着真的没有办法从提供程序中返回对象的实际TypeDescriptionProvider或其TypeDescriptor?返回类名、属性等的方法在DefaultTypeDescriptor上仍然可以正常工作,但我无法比较或找出两个对象是否使用相同的TypeDescriptor (这正是我目前所需要的)。
有人知道如何获取实际的TypeDescriptionProvider,或者如何从包装的提供程序中获取实际的TypeDescriptor吗?
提前谢谢你。
例如:
public class TestTypeDescriptionProvider : TypeDescriptionProvider
{
private static Dictionary<Type, ICustomTypeDescriptor> _descriptors = new Dictionary<Type, ICustomTypeDescriptor>();
...static method to add to the cache...
public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
{
if (objectType == null)
return _descriptors[instance.GetType()];
return _descriptors[objectType];
}
}
...
TypeDescriptionProvider p = TypeDescriptor.GetProvider(obj.GetType()); //p is a TypeDescriptionNode
ICustomTypeDescriptor td = p.GetTypeDescriptor(obj); // td is a DefaultTypeDescriptor发布于 2011-09-23 15:42:56
如果您使用诸如.NET反射器之类的工具查看TypeDescriptor.GetProvider实现,您将看到返回的类型是非常硬编码的。正如您所观察到的,它总是返回一个TypeDescriptionNode。GetTypeDescriptor的情况也是如此。
现在,您可以使用反射机制从TypeDescriptionNode获取实际的TypeDescriptionProvider。这非常简单,只需获取名为Provider的私有字段,这是TypeDescriptionNode存储实际实现的位置。当然它不受支持,但我认为这在不久的将来不会改变,我真的看不到更好的方法……
发布于 2011-09-21 04:37:55
您可以检查这两种类型是否具有相同的TypeDescriptionProviderAttribute。
https://stackoverflow.com/questions/7491422
复制相似问题