C# 返回 IWebElement (selenium) 导致 NullReferenceException

huangapple go评论179阅读模式
英文:

C# return IWebElement (selenium) causes NullReferenceException

问题

  1. public IWebDriver bot;
  2. void DataGrabber(object sender, RoutedEventArgs e)
  3. {
  4. string user = "...";
  5. string pass = "...";
  6. bot = UserLogin(user, pass);
  7. bot.Navigate().GoToUrl("https://example.com/data"); //NullReferenceException gets raised here
  8. }
  9. static IWebDriver UserLogin(string user, string pass)
  10. {
  11. IWebDriver bot = new ChromeDriver();
  12. bot.Navigate().GoToUrl("https://example.com/loginform");
  13. // Login Stuff....
  14. return bot;
  15. }
英文:

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

  1. public IWebDriver bot;
  2. void DataGrabber(object sender, RoutedEventArgs e)
  3. {
  4. string user = "...";
  5. string pass = "...";
  6. UserLogin(user, pass);
  7. bot.Navigate().GoToUrl("https://example.com/data"); //NullReferenceException gets raised here
  8. }
  9. static IWebDriver UserLogin(string user, string pass)
  10. {
  11. IWebDriver bot = new ChromeDriver();
  12. bot.Navigate().GoToUrl("https://example.com/loginform");
  13. // Login Stuff....
  14. return bot;
  15. }

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中的botDataGrabber中的bot不同。

一种解决方法:

DataGrabber中,将

  1. UserLogin(user, pass);

更改为

  1. 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

  1. UserLogin(user, pass);

to

  1. 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?

huangapple
  • 本文由 发表于 2023年8月10日 16:20:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76873869.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定