为什么我不能用相同的参数再次调用这个方法?(空引用)

本文关键字:方法 引用 调用 不能 参数 为什么 | 更新日期: 2023-09-27 18:02:05

我想我真的错过了什么,但不知道是什么。我想让这个方法返回一个web元素,但是如果有这个特定的错误,我想让它再试一次:

int findCounter = 0;
public IWebElement Find([Optional] string[] Element, [Optional] string Text)
{
   IWebElement element;
   element = null;
   if (findCounter < 30){

    if (Text != null)
    {
        Wait(null, Text);
        element = driver.FindElement(By.LinkText(Text));
        findCounter = 0;
        return element;
    }

    else
    {
        try
        {
            if (Element[1] == "xpath")
            {
                Wait(Element, null);
                element = driver.FindElement(By.XPath(Element[0]));
                findCounter = 0;
            }
            else if (Element[1] == "id")
            {
                Wait(Element, null);
                element = driver.FindElement(By.Id(Element[0]));
                findCounter = 0;
            }
            else if (Element[1] == "linktext")
            {
                Wait(Element, null);
                element = driver.FindElement(By.LinkText(Element[0]));
                findCounter = 0;                   
            }
        }
        catch (StaleElementReferenceException e)
        {
            Console.Out.WriteLine("Attempting to recover from StaleElementReferenceException ...");
            Sleep(250);
            findCounter++;
            Find(Element, Text);
        }
        return element;
    }
    }   return null;
}

所以我试了试:

Find(Element, null)

出错,输出消息,然后失败:

试图从StaleElementReferenceException中恢复…

NullReferenceException 'Object reference not set to an Object instance .'

但是我使用和第一次相同的参数。

为什么我不能用相同的参数再次调用这个方法?(空引用)

在你的catch中你还需要这个元素吗?

如果是,那么你想返回它return Find(Element, Text);

也许您必须检查传递给函数的变量"[可选]string[] Element"的值。因为int错误输出,在try块中声明一个变量为空,它不能处理,因为在catch块中错误类型是"StaleElementReferenceException"。

我的建议是再应用一个catch块来处理Null错误,并在那里放置一个断点。检查哪些值是空的,哪些不是,然后你就会意识到遗漏了什么。

示例代码:

    try
    {
        if (Element[1] == "xpath")
        {
            Wait(Element, null);
            element = driver.FindElement(By.XPath(Element[0]));
            findCounter = 0;
        }
        else if (Element[1] == "id")
        {
            Wait(Element, null);
            element = driver.FindElement(By.Id(Element[0]));
            findCounter = 0;
        }
        else if (Element[1] == "linktext")
        {
            Wait(Element, null);
            element = driver.FindElement(By.LinkText(Element[0]));
            findCounter = 0;                   
        }
    }
    catch (StaleElementReferenceException e)
    {
        Console.Out.WriteLine("Attempting to recover from StaleElementReferenceException ...");
        Sleep(250);
        findCounter++;
        Find(Element, Text);
    }
    catch (NullReferenceException e)
    {
        //break point here.
    }