温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C#如何实现天气预报功能?

发布时间:2020-06-23 11:30:17 来源:亿速云 阅读:543 作者:清晨 栏目:编程语言

这篇文章将为大家详细讲解有关C#如何实现天气预报功能?,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

引用部分

由于本次是控制台应用,就没有页面设计了。在VS中新建控制台程序后,右击“引用”——“添加服务引用”。

在“添加服务引用”左下角选择“高级”。

C#如何实现天气预报功能?

在“服务引用设置中”选择左下角的“添加web引用”。

C#如何实现天气预报功能?

在其中输入天气预报提取网址的url:

http://www.webxml.com.cn/WebServices/WeatherWebService.asmx

C#如何实现天气预报功能?

至此,引用功能就已完成。该网站提供了很多查询方法,此处我们使用的是getWeatherCityName(),方法详细内容如下:

C#如何实现天气预报功能?

当然,你也可以转到该url查看更多定义,选择适合你的方法。

代码实现部分

Main方法里直接引用:

 WeatherWebService myweather = new WeatherWebService();
      string[] myweathers = myweather.getWeatherbyCityName("郑州");
      for (int i = 0; i < myweathers.Length;i++ )
      {  Console.WriteLine(myweathers[i]);  }

传入的值尽量不要带“市”,返回的数组循环输出后结果如下:

C#如何实现天气预报功能?

其中各项所代表的含义可以查看上方官网的说明,这里为了让布局好看一点,让重点突出一点,可以使用到控制台的字体颜色转换语句:

Console.ForegroundColor = ConsoleColor.颜色;

完善后的代码如下:

 WeatherWebService myweather = new WeatherWebService();
      string[] myweathers = myweather.getWeatherbyCityName("郑州");

      Console.ForegroundColor = ConsoleColor.Red;
      Console.WriteLine("今日天气:\n更新时间:" + myweathers[4]);
      Console.WriteLine("当前选择地区:" + myweathers[0] + "_" + myweathers[1] + "\n");
      Console.ForegroundColor = ConsoleColor.White;

      Console.Write(myweathers[6] + "(今日) 风向&风力:" + myweathers[7]);
      Console.ForegroundColor = ConsoleColor.Green;
      Console.WriteLine(" 气温:" + myweathers[5] + "\n");
      Console.ForegroundColor = ConsoleColor.White;

      Console.WriteLine("当前实况(数据每2.5小时左右自动更新一次):\n" + myweathers[10] + myweathers[11]);

      Console.Write(myweathers[13] + "(明天) 风向&风力:" + myweathers[14]);
      Console.ForegroundColor = ConsoleColor.Green;
      Console.WriteLine(" 气温:" + myweathers[12] + "\n");
      Console.ForegroundColor = ConsoleColor.White;

      Console.Write(myweathers[18] + "(后天) 风向&风力:" + myweathers[19]);
      Console.ForegroundColor = ConsoleColor.Green;
      Console.WriteLine(" 气温:" + myweathers[17] + "\n");
      Console.ForegroundColor = ConsoleColor.White;

当然,你也可以在后面加一个判断,输入1的话可以查询其他城市,然后获取输入的值,传入方法中。如果感兴趣的话可以看一下源码,这里就不再过多展示。

运行效果

C#如何实现天气预报功能?

关于C#如何实现天气预报功能?就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI