C# 编码UI测试向下转换不工作

C# 编码UI测试向下转换不工作,c#,automation,coded-ui-tests,C#,Automation,Coded Ui Tests,我一直在尝试将泛型引入我们的自动化代码,因此我尝试将WpfControl转换为泛型类型T,其中T被约束为WpfControl类型 return control as T; T将始终是WpfControl的子控件,但当我将WpfControl类型的控件强制转换为泛型类型时,它将返回null。我还尝试将控件强制转换为确切的子类型,例如: var childControl = control as WpfTabList; 这仍然返回null。有人遇到过类似的问题吗 请参见以下建议: 首先,在泛型方

我一直在尝试将泛型引入我们的自动化代码,因此我尝试将WpfControl转换为泛型类型T,其中T被约束为WpfControl类型

return control as T;
T将始终是WpfControl的子控件,但当我将WpfControl类型的控件强制转换为泛型类型时,它将返回null。我还尝试将控件强制转换为确切的子类型,例如:

var childControl = control as WpfTabList;
这仍然返回
null
。有人遇到过类似的问题吗

请参见以下建议:

首先,在泛型方法中,请使用geteric类型规范。像

public T GetControl<T>(...) where T : WpfControl
public T GetControl(…),其中T:WpfControl
你的假设和实施中存在误解
您试图将
WpfControl
WpfTabList
匹配,这在子控件不是表格列表的情况下是错误的

这绝对有效。我身上有一整套的

您可以添加更多代码来显示控件的设置吗?

下面是一些摘录来说明这可能是什么样子

public static T Find<T>(this UITestControl parent) where T : UITestControl, new()
    {
        return new T() { Container = parent };
    }

public static IEnumerable<T> FindAll<T>(this UITestControl parent) where T : UITestControl, new()
    {
        return parent.Find<T>().FindAllAsType();
    }

private static IEnumerable<T> FindAllAsType<T>(this T current) where T : UITestControl, new()
    {
        if (typeof(T).IsSubclassOf(typeof(HtmlControl)))
        {
            return current.FindMatchingControls().Select(x => new T().ExtendFrom(x));
        }
        return current.FindMatchingControls().OfType<T>();
    }

private static IEnumerable<U> FindAllCastTo<T, U>(this T current) where T : UITestControl
    {
        return current.FindMatchingControls().Cast<U>();
    }
public static T Find(此UITestControl父级),其中T:UITestControl,new()
{
返回新的T(){Container=parent};
}
公共静态IEnumerable FindAll(此UITestControl父级),其中T:UITestControl,new()
{
返回parent.Find().FindAllAsType();
}
私有静态IEnumerable FindAllAsType(此T当前),其中T:UITestControl,new()
{
if(typeof(T).IsSubclassOf(typeof(HtmlControl)))
{
返回current.FindMatchingControls().Select(x=>newt().ExtendFrom(x));
}
返回类型()的当前.FindMatchingControls();
}
私有静态IEnumerable FindAllCastTo(此T当前),其中T:UITestControl
{
返回当前.FindMatchingControls().Cast();
}

最有可能的情况是控件类型不是您试图将其强制转换到的类型,或者控件类型为null

如果一切都如你所描述的那样,那么它应该会起作用。我怀疑你遗漏了什么。我建议您:a)逐步调试并查看运行时“控件”的类型,b)发布更完整的代码。还要检查控件是否为null!我以前就发现了这一点。调用构造函数的那一行-你能添加它吗。(control=new…)当你找到那条线时,你可能会自己解决它;)(如果没有,我还在这里)您还应该显示或记录
control.GetType().ToString()
,以确保它是您期望的类型。。。