【问题标题】:C# Appium/Selenium Derive WindowsElement throws error on castC# Appium/Selenium Derive WindowsElement 在转换时抛出错误
【发布时间】:2021-10-02 23:15:16
【问题描述】:

在我的 C# .NET Framework 4.8 项目中,我尝试派生 WindowsElement 类以在新类中实现一些附加功能。 例如 ClickInMiddleOfControlIsVisibleSelectedItem(在 ComboBox 中)。

public class WindowsElementWrapper : WindowsElement
{
    public WindowsElementWrapper(RemoteWebDriver parent, string id) : base(parent, id) { }

    public void ClickInMiddleOfControl()
    {
        var rect = this.Rect;
        var offsetx = (int)(0.5 * rect.Width);
        var offsety = (int)(0.5 * rect.Height);
        new Actions(Helper.Session)
            .MoveToElement(this, 0, 0)
            .MoveByOffset(offsetx, offsety)
            .Click()
            .Build()
            .Perform();
    }
}

然后我尝试将 WindowsElement 强制转换为我的 WindowsElementWrapper。

var element = (WindowsElementWrapper)Session.FindElementByName("ElementName");
element.ClickInMiddleOfControl();

但在运行时我收到以下错误消息:

System.InvalidCastException: '无法转换类型的对象 OpenQA.Selenium.Appium.Windows.WindowsElement' 输入 'WEW.WindowsElementWrapper'。'

不能从 WindowsElement 类派生吗?还是我犯了一个根本性的错误?

【问题讨论】:

    标签: c# appium


    【解决方案1】:

    WindowsElementWindowsElementWrapper 的转换是沮丧

    为了使向下转型成功,对象的运行时类型必须是目标类型本身,或者是从它派生的类型。

    虽然WindowsElementWrapperWindowsElement,但WindowsElement 不一定是WindowsElementWrapper

    换句话说,这种向下转换永远不会成功,除非 SeleniumAPI 以 WindowsElementWrapper 开头的对象实例化

    为了实现你想做的事情,你可以应用以下设计之一:


    作曲

    public class WindowsElementWrapper
    {
       private readonly WindowsElement element;
    
       public WindowsElementWrapper(WindowsElement element, (int Width, int Height) rect)
       {
          this.element = element;
          Rect = rect;
       }
    
       public (int Width, int Height) Rect { get; init; }
    
       public void ClickInMiddleOfControl()
          => new Actions(Helper.Session)
                .MoveToElement(element, 0, 0)
                .MoveByOffset(Rect.Width / 2, Rect.Height / 2)
                .Click()
                .Build()
                .Perform();
    }
    

    扩展方法

    public static class Extensions
    {
       public static void ClickInMiddleOfControl(this WindowsElement source, (int Width, int Height) rect)
          => new Actions(Helper.Session)
                .MoveToElement(source, 0, 0)
                .MoveByOffset(rect.Width / 2, rect.Height / 2)
                .Click()
                .Build()
                .Perform();
    }
    

    最好的问候

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-29
      • 2018-10-14
      • 1970-01-01
      相关资源
      最近更新 更多