英文:
C# return IWebElement (selenium) causes NullReferenceException
问题
public IWebDriver bot;
void DataGrabber(object sender, RoutedEventArgs e)
{
string user = "...";
string pass = "...";
bot = UserLogin(user, pass);
bot.Navigate().GoToUrl("https://example.com/data"); //NullReferenceException gets raised here
}
static IWebDriver UserLogin(string user, string pass)
{
IWebDriver bot = new ChromeDriver();
bot.Navigate().GoToUrl("https://example.com/loginform");
// Login Stuff....
return bot;
}
英文:
I am new to C# and working with methods. My attempt was to create a seperate method for logging the user in. The Code looks something like
public IWebDriver bot;
void DataGrabber(object sender, RoutedEventArgs e)
{
string user = "...";
string pass = "...";
UserLogin(user, pass);
bot.Navigate().GoToUrl("https://example.com/data"); //NullReferenceException gets raised here
}
static IWebDriver UserLogin(string user, string pass)
{
IWebDriver bot = new ChromeDriver();
bot.Navigate().GoToUrl("https://example.com/loginform");
// Login Stuff....
return bot;
}
how do I properly define bot, so that the DataGrabber() method knows what it is?
I removed the public IWebDriver bot;
definition in the beginning but that just results in the bot not being recognized as a variable at all ("The name "bot" is not available in the current context").
I also attempted to move the UserLogin() method before the DataGrabber() method, but this did not help (bot still not recognized within DataGrabber() function).
I am certain that this is an easy thing to answer, however searching online did not return anything useful
答案1
得分: 1
你从UserLogin
中返回(本地变量)bot
,但你从未将其分配给类级别字段。换句话说:UserLogin
中的bot
与DataGrabber
中的bot
不同。
一种解决方法:
在DataGrabber
中,将
UserLogin(user, pass);
更改为
bot = UserLogin(user, pass);
以设置类级别字段。
有关该异常的更多详细信息,请参见什么是NullReferenceException,我该如何修复它?。
英文:
You return (the local variable) bot
from UserLogin
, but you never assign it to the class-level field. In other words: the bot
in UserLogin is different from the bot
in DataGrabber.
One solution:
in DataGrabber, change
UserLogin(user, pass);
to
bot = UserLogin(user, pass);
to set the class-level field.
For further details about that exception, see What is a NullReferenceException, and how do I fix it?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论