【问题标题】:Is there any way to check the type regardless its inheritance tree? but inside of function [duplicate]有没有办法检查类型而不管它的继承树?但在函数内部[重复]
【发布时间】:2018-07-05 19:01:43
【问题描述】:

我想在 Canvas 的子级中检查类类型,而不考虑继承树。所以我做了一个像下面这样的可重用函数。

private int FindIndexOf(Type _t)
    {
        if (wrappingGrid == null)
            return -1;

        for(int i =0; i< wrappingGrid.Children.Count; ++i)
        {
            if(wrappingGrid.Children[i].GetType() == _t)
            {
                return i;
            }
        }
        return -1;
    }

但它只适用于类型严格。

wrappingGrid.Children[i] is _t

这也不起作用,因为“类型”类型不是我想要比较的。它会导致语法错误。 可能我需要制作一个模板功能。 但我最好写更简单的代码。

我也已经查看了其他文章。 Type Checking: typeof, GetType, or is?

你有什么想法吗? 提前谢谢你..

【问题讨论】:

  • 试试_t.IsAssignableFrom(wrappingGrid.Children[i].GetType())

标签: c# wpf types gettype


【解决方案1】:

也许你应该试试wrappingGrid.Children[i].GetType().IsSubClassOf(_t)

编辑 @usr: 是的:IsAssignableFrom 更好,但反之亦然:

_t.IsAssignableFrom(wrappingGrid.Children[i].GetType()

【讨论】:

  • 我认为 IsSubClassOf 对相等类型说 false 。您必须使用 IsAssignableFrom。
猜你喜欢
  • 1970-01-01
  • 2011-10-29
  • 1970-01-01
  • 1970-01-01
  • 2011-02-16
  • 2010-09-28
  • 1970-01-01
  • 1970-01-01
  • 2011-01-14
相关资源
最近更新 更多