wsdl 架构验证警告:来自命名空间_【C#基础】名称空间:你真的了解using System吗?...

using System是C#中引用System命名空间的语法,用于访问常用的类和类型。System命名空间包含了基础类、数据类型、异常处理等核心元素。随着开发工具的进步,自动引入命名空间的功能可能使开发者对其工作原理了解不足。了解using System的本质对于提升编码效率和理解代码结构至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1177b38e1e5ba9243ad780b33055d4f1.gif

22e896c299c695078928b0cb71a2bfe3.png

    using System的意思是引用名称为System的命名空间。命名空间提供了一种组织相关类和其他类型的方式。命名空间的设计目的是提供一种让一组名称与其他名称分隔开的方式。

    实际上命名空间是用来组织和重用代码的。如同名字一样的意思,命名空间是唯一识别的一套名字,这样当对象来自不同的地方但是名字相同的时候就不会含糊不清了。

     using 是C# 语言中定义一个范围,将在此范围之外释放一个或多个对象。

    System 命名空间包含用于定义常用值和引用数据类型、事件和事件处理程序、接口、特性以及处理异常的基础类和基类。

常见引入的命名空间如下
using System;
using System.Collections;
u
using System; using System.IO; using System.Text.RegularExpressions; using System.Windows.Forms; using Microsoft.Win32; namespace MRU { public partial class FormMRU : Form { public FormMRU() { #region InitializeComponent(); ListView listViewMRU = new ListView(); listViewMRU.Dock = DockStyle.Fill; listViewMRU.HeaderStyle = ColumnHeaderStyle.None; // 隐藏列标题。 listViewMRU.View = View.Details; // 详细信息。 listViewMRU.CheckBoxes = true; // 显示复选框。 listViewMRU.Scrollable = false; // 隐藏滚动条。 listViewMRU.ShowGroups = true; // 分组显示项。 listViewMRU.BeginUpdate(); ListViewGroup pro = listViewMRU.Groups.Add("profile", "profile"); listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.Recent)).Group = pro; listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.Cookies)).Group = pro; listViewMRU.Items.Add(Path.GetTempPath()).Group = pro; listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.History)).Group = pro; listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache)).Group = pro; ListViewGroup reg = listViewMRU.Groups.Add("regedit", "regedit"); listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\TypedURLs").Group = reg; listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU").Group = reg; listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32").Group = reg; listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Paint").Group = reg; listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Wordpad").Group = reg; ColumnHeader column = listViewMRU.Columns.Add(""); column.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent); // 自动调整列宽。 listViewMRU.EndUpdate(); listViewMRU.ItemChecked += new ItemCheckedEventHandler(listViewMRU_ItemChecked); this.Controls.Add(listViewMRU); this.ClientSize = new System.Drawing.Size(column.Width + 8, 260); this.Text = Environment.UserName; this.AutoSizeMode = AutoSizeMode.GrowAndShrink; // 禁用手动调整大小。 this.SizeGripStyle = SizeGripStyle.Hide; // 隐藏调整大小手柄。 this.StartPosition = FormStartPosition.CenterScreen; // 在桌面居中显示。 #endregion } #region ListView_ItemChecked private void listViewMRU_ItemChecked(object sender, ItemCheckedEventArgs e) { if (!e.Item.Checked) return; DirectoryInfo dir = new DirectoryInfo(e.Item.Text); switch (e.Item.Index) { case 0: case 1: foreach (FileInfo info in dir.GetFiles()) { if (Regex.IsMatch(info.Extension, @".(dat|ini)", RegexOptions.IgnoreCase)) // 指定不区分大小写的匹配。 continue; this.Text = info.Name; info.Delete(); } break; case 2: foreach (FileSystemInfo info in dir.GetFileSystemInfos()) { try { if (info is FileInfo) info.Delete(); else (info as DirectoryInfo).Delete(true); } catch { continue; } finally { this.Text = info.Name; } } break; case 3: System.Diagnostics.Process.Start(e.Item.Text); break; case 4: foreach (FileInfo info in dir.GetFiles("*.*", SearchOption.AllDirectories)) { if (Regex.IsMatch(info.Extension, @".(dat|ini)", RegexOptions.IgnoreCase)) // 指定不区分大小写的匹配。 continue; try { info.Delete(); } catch { continue; } finally { this.Text = info.Name; } } break; case 5: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Internet Explorer\TypedURLs")) { foreach (string mru in subKey.GetValueNames()) { subKey.DeleteValue(mru); } } break; case 6: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU")) { foreach (string mru in subKey.GetValueNames()) { subKey.DeleteValue(mru); } } break; case 7: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32")) { foreach (string mru in subKey.GetSubKeyNames()) { subKey.DeleteSubKeyTree(mru); } } break; case 8: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Applets\Paint\Recent File List")) { foreach (string mru in subKey.GetValueNames()) { subKey.DeleteValue(mru); } } break; case 9: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Applets\Wordpad\Recent File List")) { foreach (string mru in subKey.GetValueNames()) { subKey.DeleteValue(mru); } } break; } this.Text = Environment.UserName; } #endregion } }using System; using System.IO; using System.Text.RegularExpressions; using System.Windows.Forms; using Microsoft.Win32; namespace MRU { public partial class FormMRU : Form { public FormMRU() { #region InitializeComponent(); ListView listViewMRU = new ListView(); listViewMRU.Dock = DockStyle.Fill; listViewMRU.HeaderStyle = ColumnHeaderStyle.None; // 隐藏列标题。 listViewMRU.View = View.Details; // 详细信息。 listViewMRU.CheckBoxes = true; // 显示复选框。 listViewMRU.Scrollable = false; // 隐藏滚动条。 listViewMRU.ShowGroups = true; // 分组显示项。 listViewMRU.BeginUpdate(); ListViewGroup pro = listViewMRU.Groups.Add("profile", "profile"); listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.Recent)).Group = pro; listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.Cookies)).Group = pro; listViewMRU.Items.Add(Path.GetTempPath()).Group = pro; listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.History)).Group = pro; listViewMRU.Items.Add(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache)).Group = pro; ListViewGroup reg = listViewMRU.Groups.Add("regedit", "regedit"); listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\TypedURLs").Group = reg; listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU").Group = reg; listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32").Group = reg; listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Paint").Group = reg; listViewMRU.Items.Add(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Applets\Wordpad").Group = reg; ColumnHeader column = listViewMRU.Columns.Add(""); column.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent); // 自动调整列宽。 listViewMRU.EndUpdate(); listViewMRU.ItemChecked += new ItemCheckedEventHandler(listViewMRU_ItemChecked); this.Controls.Add(listViewMRU); this.ClientSize = new System.Drawing.Size(column.Width + 8, 260); this.Text = Environment.UserName; this.AutoSizeMode = AutoSizeMode.GrowAndShrink; // 禁用手动调整大小。 this.SizeGripStyle = SizeGripStyle.Hide; // 隐藏调整大小手柄。 this.StartPosition = FormStartPosition.CenterScreen; // 在桌面居中显示。 #endregion } #region ListView_ItemChecked private void listViewMRU_ItemChecked(object sender, ItemCheckedEventArgs e) { if (!e.Item.Checked) return; DirectoryInfo dir = new DirectoryInfo(e.Item.Text); switch (e.Item.Index) { case 0: case 1: foreach (FileInfo info in dir.GetFiles()) { if (Regex.IsMatch(info.Extension, @".(dat|ini)", RegexOptions.IgnoreCase)) // 指定不区分大小写的匹配。 continue; this.Text = info.Name; info.Delete(); } break; case 2: foreach (FileSystemInfo info in dir.GetFileSystemInfos()) { try { if (info is FileInfo) info.Delete(); else (info as DirectoryInfo).Delete(true); } catch { continue; } finally { this.Text = info.Name; } } break; case 3: System.Diagnostics.Process.Start(e.Item.Text); break; case 4: foreach (FileInfo info in dir.GetFiles("*.*", SearchOption.AllDirectories)) { if (Regex.IsMatch(info.Extension, @".(dat|ini)", RegexOptions.IgnoreCase)) // 指定不区分大小写的匹配。 continue; try { info.Delete(); } catch { continue; } finally { this.Text = info.Name; } } break; case 5: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Internet Explorer\TypedURLs")) { foreach (string mru in subKey.GetValueNames()) { subKey.DeleteValue(mru); } } break; case 6: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU")) { foreach (string mru in subKey.GetValueNames()) { subKey.DeleteValue(mru); } } break; case 7: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32")) { foreach (string mru in subKey.GetSubKeyNames()) { subKey.DeleteSubKeyTree(mru); } } break; case 8: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Applets\Paint\Recent File List")) { foreach (string mru in subKey.GetValueNames()) { subKey.DeleteValue(mru); } } break; case 9: using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Applets\Wordpad\Recent File List")) { foreach (string mru in subKey.GetValueNames()) { subKey.DeleteValue(mru); } } break; } this.Text = Environment.UserName; } #endregion } }
<think>我们之前讨论的是在无法直接访问服务元数据地址时,如何手动下载WSDL和XSD文件并生成客户端代码。现在用户明确要求:如何在C#中使用System.ServiceModel引入(即使用)本地WSDL和XSD文件生成的客户端代码。回顾我们之前的步骤,已经使用svcutil.exe生成了两个文件:-客户端代码文件(如Client.cs)-配置文件(如app.config)现在,用户需要知道如何在C#项目中使用这些生成的代码。以下是具体步骤:###1.**将生成的文件添加到项目中**-将生成的`Client.cs`(或你命名的代码文件)和`app.config`(或你命名的配置文件)添加到你的C#项目中。-如果使用VisualStudio,可以直接拖拽到项目中,或者右键项目->添加->现有项。###2.**确保引用了必要的程序集**-生成的客户端代码依赖于`System.ServiceModel`等程序集。请确保你的项目引用了这些程序集。通常,在创建新的控制台应用程序或ASP.NET项目时,这些引用已经存在。如果没有,请通过NuGet添加:```bashInstall-PackageSystem.ServiceModel.PrimitivesInstall-PackageSystem.ServiceModel.Http```###3.**使用生成的客户端类**-生成的代码中会包含一个与服务同名的客户端类,例如如果服务名为`WeatherWebService`,则生成类可能为`WeatherWebServiceClient`(具体名称取决于WSDL中的定义)。-在代码中,你可以像使用普通类一样实例化这个客户端类,并调用其方法。###4.**配置终结点(可选)**-如果你在生成代码时使用了`/config`选项,那么`app.config`(或`web.config`)中已经包含了服务的配置信息,特别是终结点地址。你可以在配置文件中修改这个地址,而无需重新生成代码。-如果服务地址发生了变化,你只需要更新配置文件中的`<endpointaddress="...">`。###5.**调用服务**-在代码中,实例化客户端,然后调用方法。例如:```csharpusingSystem;namespaceYourNamespace{classProgram{staticvoidMain(string[]args){//使用生成的客户端类WeatherWebServiceClientclient=newWeatherWebServiceClient();try{//调用服务方法stringresult=client.SomeMethod();Console.WriteLine(result);//记得关闭客户端client.Close();}catch(Exceptionex){//异常处理Console.WriteLine(ex.Message);client.Abort();}}}}```###6.**注意异常处理和资源释放**-因为WCF客户端可能占用网络资源,所以需要确保在出现异常时能够正确释放资源。上面的例子中使用了`try-catch`,并在异常时调用`Abort()`,正常时调用`Close()`。###7.**重新生成客户端代码的时机**-如果服务接口发生了变化(例如添加了新方法或修改了参数),你需要重新下载WSDL和XSD,并重新生成客户端代码,然后替换项目中的旧文件。###代码示例(基于引用[3])引用[3]中展示了一个使用生成的客户端代码的示例:```csharp//使用生成的客户端ServiceReference1.ContractClientclient=newServiceReference1.ContractClient();IList<ServiceReference1.User>lst=client.getlist();```这里,`ServiceReference1`是生成代码的命名空间,`ContractClient`是生成的客户端类。###配置文件示例(基于引用[4])引用[4]展示了另一种以编程方式生成代码的方法,但用户已经生成了代码,所以我们关注配置文件。在`app.config`中通常会有如下配置:```xml<system.serviceModel><bindings><!--绑定配置--></bindings><client><endpointaddress="http://service-domain/path"binding="basicHttpBinding"contract="ServiceReference1.IContract"/></client></system.serviceModel>```###针对用户的问题总结-**引入本地生成的客户端代码**:实际上就是将生成的代码文件(Client.cs)和配置文件(app.config)添加到项目中,然后在代码中直接实例化客户端类即可。-如果出现端点地址错误(如第一个相关问题),可以修改配置文件中的地址,而无需重新生成代码(除非服务合同发生了变化)。---§§相关问题§§1.如何更新已生成的客户端代码以适应服务端变化?2.生成的客户端代码中缺少某些方法怎么办?3..NETCore项目中如何使用System.ServiceModel生成和引入客户端代码?</think> ### 在 C# 中使用 System.ServiceModel 引入本地生成的客户端代码 以下是完整实现步骤(基于引用[1][2][4]): #### 1. **生成客户端代码** 首先使用 svcutil.exe 生成客户端代理类: ```bash svcutil.exe /language:cs /out:ServiceClient.cs service.wsdl types.xsd ``` 这会生成两个关键文件: - `ServiceClient.cs` - 包含客户端代理类和服务契约 - `output.config` - 包含服务模型配置(引用[1][2]) #### 2. **在项目中添加代理类** 将生成的 `ServiceClient.cs` 文件添加到项目中: ```csharp // 生成的代理类示例(部分内容) [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public partial class ServiceClient : System.ServiceModel.ClientBase<IServiceContract>, IServiceContract { public ServiceClient() { } public ResponseData GetData(RequestParams request) { return base.Channel.GetData(request); } } [ServiceContract] public interface IServiceContract { [OperationContract] ResponseData GetData(RequestParams request); } ``` #### 3. **配置服务终结点** 在 `App.config` 或 `Web.config` 中添加服务配置(引用[4]): ```xml <system.serviceModel> <client> <endpoint address="https://your-service-endpoint" binding="basicHttpBinding" contract="YourNamespace.IServiceContract" name="ServiceEndpoint"/> </client> </system.serviceModel> ``` #### 4. **在代码中使用客户端** 通过代理类调用服务方法(引用[1][3]): ```csharp using System.ServiceModel; public class ServiceConsumer { public void CallService() { // 使用配置文件中的默认配置 using (var client = new ServiceClient()) { try { var request = new RequestParams { /* 填充参数 */ }; ResponseData response = client.GetData(request); // 处理响应数据 Console.WriteLine(response.Result); client.Close(); // 正常关闭 } catch (CommunicationException e) { client.Abort(); // 通信异常时中止 } catch (TimeoutException e) { client.Abort(); // 超时异常时中止 } } } } ``` #### 关键注意事项: 1. **端点配置管理** - 修改服务地址无需重新编译代码: ```xml <endpoint address="https://new-server-url" ... /> ``` 2. **自定义绑定配置** ```xml <bindings> <basicHttpBinding> <binding name="SecureBinding" maxReceivedMessageSize="65536" securityMode="Transport"> <security mode="Transport" /> </binding> </basicHttpBinding> </bindings> ``` 3. **异常处理最佳实践** - 使用 `using` 语句确保资源释放 - 对不同的 WCF 异常类型进行区别处理 - 总是包含 `Close()`/`Abort()` 调用(引用[1][3]) #### 5. **高级应用场景** 1. **手动加载配置**(引用[4]) ```csharp var binding = new BasicHttpBinding(); var endpoint = new EndpointAddress("https://custom-endpoint"); using (var client = new ServiceClient(binding, endpoint)) { // 调用方法 } ``` 2. **动态配置** ```csharp var client = new ServiceClient("CustomEndpointName"); ``` #### 常见问题解决: - **配置不匹配错误**:检查终结点名称与构造函数参数是否一致 - **序列化问题**:确保服务端和客户端共享相同的数据契约 - **连接超时**:在绑定配置中调整 `receiveTimeout`/`sendTimeout` > ⚠️ 最佳实践:每次服务更新后,需要重新下载 WSDL/XSD 并重新生成客户端代理类(引用[1])[^1][^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值