【问题标题】:Checking for object type compatibility at runtime在运行时检查对象类型兼容性
【发布时间】: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;
}

【问题讨论】:

    标签: c# types


    【解决方案1】:

    您可以使用 Type.IsAssignableFrom 例如

    public class Foo { }
    
    public class Bar : Foo { }
    
    ...
    
    bool compatible = typeof(Foo).IsAssignableFrom(typeof(Bar));
    

    【讨论】:

    • FooBar 是类型 - 我需要比较实例的类型,例如var foo == new Foo(); Type bar = typeof(someType); ... foo 类型与 bar 兼容吗?
    • 如果不能表达类型转换或比较(例如if (someInstance is Foo)Foo checkInstance = someInstance as Foo),则需要获取类型。因此,在上面的示例中,您需要检查 foo.GetType() 并将其与 IsAssignableFrom 一起使用。
    猜你喜欢
    • 2018-07-29
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 2018-01-15
    • 2013-11-02
    • 1970-01-01
    • 2020-08-27
    相关资源
    最近更新 更多