• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

C#实现简单的天气预报示例代码

c# 搞代码 4年前 (2022-01-09) 18次浏览 已收录 0个评论

前言

本来是打算用C#爬取天气网站上的信息,然后用正则表达过滤有用信息的,但是很淦,正则表达式太难了。无意间找到添加web引用的方式来获取天气信息,亲自测试后发现效果尚可,就记录一下。

引用部分

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

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

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

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

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

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

当然,你也可以转到该url查看更多本文来源[email protected]搞@^&代*@码)网9定义,选择适合你的方法。

代码实现部分

Main方法里直接引用:

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

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

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

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# 天气预报内容请搜索搞代码以前的文章或继续浏览下面的相关文章希望大家以后多多支持搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:C#实现简单的天气预报示例代码

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址