You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何忽略继承关系检查Canvas子元素类类型?求简洁实现方案

Solution for Runtime Type Checking with Inheritance Support

Great question! The issue here is that the is operator expects a compile-time type name, not a runtime Type object—so that's why you're hitting a syntax error. Luckily, the Type class has built-in methods to handle exactly this kind of runtime type checking for inheritance/implementation relationships.

Fix the Function with IsInstanceOfType

The simplest way to modify your existing function to support inheritance checks is to use Type.IsInstanceOfType(object). This method returns true if the provided object is an instance of the target type or any derived type/interface implementation.

Here's the updated code:

private int FindIndexOf(Type targetType) {
    if (wrappingGrid == null) return -1;
    for(int i = 0; i < wrappingGrid.Children.Count; ++i) {
        var child = wrappingGrid.Children[i];
        // Checks if child is of targetType OR a subtype/implementation
        if (targetType.IsInstanceOfType(child)) {
            return i;
        }
    }
    return -1;
}

Alternative: IsAssignableFrom

If you prefer working directly with the type of the child element, you can use Type.IsAssignableFrom(Type) instead. Just make sure to reverse the order of the check (the target type comes first):

if (targetType.IsAssignableFrom(child.GetType()))

This does the same thing as IsInstanceOfType—it verifies if an instance of the child's type can be assigned to a variable of targetType, which covers inheritance and interface implementations.

Why This Works

  • Your original GetType() == targetType only matches exact type equivalents.
  • IsInstanceOfType and IsAssignableFrom respect the type hierarchy, which is exactly what you need to ignore strict inheritance boundaries and find any compatible child element.
  • This approach keeps your function non-generic, using a runtime Type parameter as requested, while maintaining clean, readable code.

内容的提问来源于stack exchange,提问作者Tangibleidea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:27:04