如何忽略继承关系检查Canvas子元素类类型?求简洁实现方案
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() == targetTypeonly matches exact type equivalents. IsInstanceOfTypeandIsAssignableFromrespect 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
Typeparameter as requested, while maintaining clean, readable code.
内容的提问来源于stack exchange,提问作者Tangibleidea

