【发布时间】:2011-03-11 13:50:30
【问题描述】:
这是一个非常笼统的问题,但我正在做的具体事情很简单,所以我将代码包括在内。当我在编译时不知道任何一个对象的类型时,如何检查两个对象之间的类型兼容性?
也就是说,当SomeType 是编译时已知的类型名称时,我可以使用if (object is SomeType)。 GetType() 是不够的,因为它不适用于派生类型。基本上我想说,if (object.IsTypeOfOrIsDerivedFrom(someType)) 这个神奇方法的 sig 是IsTypeOfOrIsDerivedFrom(Type type)
这是上下文。
// Return all controls that are (or are derived from) any of a list of Types
public static IEnumerable<Control> FindControls(this Control control, IEnumerable<Type> types, bool recurse)
{
foreach (Control ctl in control.Controls)
{
/// How can I compare the base types of item & ctl?
if (types.Any(item=> .... ))
{
yield return (ctl);
}
if (recurse && ctl.Controls.Count > 0)
{
IEnumerable<Control> subCtl = ctl.FindControls(types,true);
if (subCtl != null)
{
yield return (subCtl);
}
}
}
yield break;
}
【问题讨论】: