简体   繁体   中英

C# Get cast exception with implemented explicit cast

I have outer function:

public int SetHeight(IWebElement column)
{
    ExtendedElement.Get(column).Click();
}

the column parameter it recieves in the call is of concrete type ExtendedElement already, but since it accepts any IWebElement I need that Get method.

Here's ExtendedElement important parts:

public class ExtendedElement : IWebElement
{
    private IWebElement _Element { get; set; }
    private ExtendedElement() {}

    public static ExtendedElement Get(IWebElement element)
    {
        return new ExtendedElement()
        {
            _Element = (RemoteWebElement)element
        };
    }

    public static explicit operator RemoteWebElement(ExtendedElement element)
    {
        return (RemoteWebElement)element._Element;
    }
    // other impmlementations
}

How to write the conversion I read from Microsoft

And for some reason when the code is run I get the exception: System.InvalidCastException : Unable to cast object of type 'Core.Helper.ExtendedElement' to type 'OpenQA.Selenium.Remote.RemoteWebElement'.

So, why's that? And if I'm over-complicating things and need to change the design - what should aim for?

To implement a customized web element which keeps its original methods, extend RemoteWebElement :

public class ExtendedElement : RemoteWebElement
{

    public static ExtendedElement Get(IWebElement element)
    {
        RemoteWebDriver driver = (RemoteWebDriver)element.WrappedDriver;
        string id = (string)typeof(RemoteWebElement)
                        .GetProperty("Id", BindingFlags.NonPublic | BindingFlags.Instance)
                        .GetValue(element, null);

        return new ExtendedElement(driver, id);
    }

    public ExtendedElement(RemoteWebDriver driver, string id)
        : base(driver, id)
    { }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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