Checking for object type compatibility at runtime
This is a pretty general question, but the specific thing I'm doing is simple so I'm including the code. How do I check for type compatibility between two objects when I don't know the type of either at compile time?
That is, I can do if (object is SomeType)
when SomeType
is a type name known at compile time. GetType()
is not sufficient because it will not work with derived types. Basically I want to be able to say, if (object.IsTypeOfOrIsDerivedFrom(someType))
where sig of this magical method is IsTypeOfOrIsDerivedFrom(Type type)
Here is the context.
// 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);
开发者_如何学Go }
if (recurse && ctl.Controls.Count > 0)
{
IEnumerable<Control> subCtl = ctl.FindControls(types,true);
if (subCtl != null)
{
yield return (subCtl);
}
}
}
yield break;
}
You can use, Type.IsAssignableFrom
e.g.
public class Foo { }
public class Bar : Foo { }
...
bool compatible = typeof(Foo).IsAssignableFrom(typeof(Bar));
精彩评论