能否在Visual Studio 2017中为WinForm添加WebClient至InitializeComponent?
不行哦,System.Net.WebClient没办法直接像BackgroundWorker那样通过Visual Studio的窗体设计器添加到Form里,也没法让设计器自动在InitializeComponent()中生成它的实例化代码——核心原因是WebClient并没有实现System.ComponentModel.IComponent接口(也没有继承自Component类),而设计器里能拖到窗体组件托盘、自动生成初始化代码的控件/组件,都必须是Component的子类(或者实现IComponent),这样设计器才能识别并管理它们的生命周期和配置。
而BackgroundWorker之所以可以,就是因为它继承自Component,属于设计器支持的“可视化组件”范畴,拖到窗体后,设计器会自动在InitializeComponent()里完成实例化、事件绑定等代码。
那如果一定要让WebClient的实例化代码出现在InitializeComponent()里,有没有办法?有两个思路:
不推荐:手动修改InitializeComponent()
你可以自己手动在InitializeComponent()里添加WebClient的实例化代码,但要注意:这个方法是设计器自动生成的,每次你在设计器里修改窗体,Visual Studio都可能重新生成这个方法,你手动加的代码大概率会被覆盖,所以非常不建议这么做。推荐:自定义WebClient的Component包装类
你可以写一个继承自Component的包装类,把WebClient封装进去,这样这个包装类就能被设计器识别,拖到窗体组件托盘里,设计器会自动在InitializeComponent()里生成它的初始化代码。
举个简单的包装类例子:
using System.ComponentModel; using System.Net; public class WebClientComponent : Component { private WebClient _webClient; // 对外暴露WebClient实例,方便调用它的方法 public WebClient WebClientInstance => _webClient ?? (_webClient = new WebClient()); // 把WebClient的常用事件暴露出来,方便在设计器里绑定事件处理方法 public event DownloadStringCompletedEventHandler DownloadStringCompleted { add => WebClientInstance.DownloadStringCompleted += value; remove => WebClientInstance.DownloadStringCompleted -= value; } public event DownloadDataCompletedEventHandler DownloadDataCompleted { add => WebClientInstance.DownloadDataCompleted += value; remove => WebClientInstance.DownloadDataCompleted -= value; } // 重写Dispose方法,确保WebClient被正确释放 protected override void Dispose(bool disposing) { if (disposing && _webClient != null) { _webClient.Dispose(); _webClient = null; } base.Dispose(disposing); } }
写完这个类后,重新生成你的项目,就能在Visual Studio的工具箱里找到WebClientComponent了,把它拖到窗体的组件托盘里,设计器就会自动在InitializeComponent()里生成它的实例化代码。之后你就可以通过这个组件的WebClientInstance属性来调用WebClient的所有方法,还能在设计器里直接绑定它的事件,和使用BackgroundWorker的体验差不多~
内容的提问来源于stack exchange,提问作者user8649828

