[英]How to fix: Use of unassigned local IWebElement variable
For the following code, 对于以下代码,
IWebElement element; // = new WebElement();
try
{
element = driver.FindElement(By...);
}
catch (Exception)
{
}
element.Click();
How to fix the error of Use of unassigned local variable
? 如何修复Use of unassigned local variable
的错误?
I know for the error of Use of unassigned local variable
, the fix is to assign it with something initially, but I've tried new WebElement();
我知道Use of unassigned local variable
的错误,修复是最初为它分配的东西,但我尝试了new WebElement();
and new IWebElement();
和new IWebElement();
but they didn't work for me. 但他们不适合我。
Any help? 有帮助吗?
PS. PS。 I was trying in the catch
statement to loop and find it, that's why I need the element declaration outside of try
, and Click()
after it. 我试图在catch
语句中循环并找到它,这就是为什么我需要在try
之外的元素声明,然后在它之后的Click()
。
The compiler helps to fix a bug. 编译器有助于修复错误。 He's telling you that this will fail with a NullReferenceException
at element.Click()
if there was an exception during initialization of element
. 他告诉大家,这将与失败NullReferenceException
在element.Click()
如果有初始化期间的异常element
。 So he wants you to assign something in any case(or as default value). 所以他希望你在任何情况下(或默认值)分配一些东西。 You have multiple options to fix... 你有多个选择来修复......
Use the object after the initialization in the try
: 在try
初始化后使用该对象:
try
{
element = driver.FindElement(By...);
element.Click(); // safe because there was no exception
}
catch (Exception)
{
// empty catch is bad, log this at least
}
"Hide" the compiler error but let the potential bug live by assigning something to the variable: “隐藏”编译器错误,但通过为变量分配内容来让潜在的bug生效:
IWebElement element = null;
try
{
element = driver.FindElement(By...);
}
catch (Exception)
{
// empty catch is bad, log this at least
}
element.Click(); // still a bug if there was an exception this will cause a NullReferenceException
this option is perfectly fine if you use if(element != null) element.Click();
如果你使用if(element != null) element.Click();
这个选项就完全没了问题if(element != null) element.Click();
instead. 代替。
Or you could use the catch
/ finally
to assign something (imo worst option here): 或者你可以使用catch
/ finally
来分配一些东西(imo最糟糕的选择):
IWebElement element;
try
{
element = driver.FindElement(By...);
}
catch (Exception)
{
element = null;
}
But then you have to check for null
, either with if(element != null)
or with: 但是你必须检查null
,使用if(element != null)
或者:
element?.Click(); // if not null Click is called
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.