繁体   English   中英

如何在不指定类型的不同 class 列表中找到通用 UI class?

[英]how to find a generic UI class in a list of different class without specifying the type?

在此处输入图像描述

我制作了一个名为 DraggableLayout 的通用 UI class。 这是一个嵌套在其他 DraggableLayout 中的树状布局

问题是,当我循环浏览父母中的控件列表时,我需要孩子们能够搜索 DraggableLayout。

        foreach (var tab in Parents)
        {
            if (tab is DraggableLayout) //Error CS0305
            {
               //Do Something
            }
        }

当我执行上述操作时,我需要指定类型。 是否可以忽略并搜索父通用 class?

你可以做的是:

var tabType = tab.GetType();
if (tabType.IsGenericType
    && typeof(DraggableLayout<>)
        .IsAssignableFrom(tabType.GetGenericTypeDefinition()))
{ ... }

或者使用扩展方法:

public static bool IsOfGenericType(this Type source, Type genericType)
{
    return source.IsGenericType
        && genericType.IsAssignableFrom(source.GetGenericTypeDefinition());
}

// ...
if (typeof(tab).IsOfGenericType(typeof(DraggableLayout<>)))
{ ... }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM