C#:为特定的代码块使用命名空间?
我只是有好奇心。 我正在使用SSRS并调用其SOAP方法。 我已经生成了存根/创建了Web引用,并且一切正常,我可以使Web服务调用正常。
问题:从WSDL,ReportService2005和ReportExecution生成的两个类有一些重叠的类定义,例如ParameterValue,DataSourceCredentials,ReportParameter。
在C#中,有没有办法说,“对于方法中的这个代码块,使用这个命名空间?”
伪/主要是构建错误代码:
use-this-namespace (ReportService2005) { ParameterValue[] values = null; DataSourceCredentials[] credentials = null; ReportParameter[] parameters; }
据我所知,我只能写出全名,ReportService2005.ParameterValue [] values = null。 或者我可以在我的类/控制器声明之前在顶部对两个类进行别名。 这只是我很好奇的事情。
正如其他人所写,我认为这是不可能的。 但是你可以做的是将完整的命名空间别名,而不是你想要使用的每个单独的类,例如:
using rs = ReportService2005; using re = ReportExecution; // ... rs.ParameterValue[] values = null; rs.DataSourceCredentials[] credentials = null; rs.ReportParameter[] parameters; re.ParameterValue v2 = ...;
另一个鲜为人知的C#function可能会引起您的兴趣,与Martin的答案类似,它基本上是对Imports
块中的类别名:
using ListOfDictionary = System.Collections.Generic.List>;
并声明为
ListOfDictionary list = new ListOfDictionary();
注意此function和示例在另一个问题中找到; 具体来说: C#的隐藏function?
我认为你不能这样做。 您必须指定完全限定名称才能执行此操作。
您可以做的是将您的课程标记为部分:
public partial class MyWebServiceClass
在主源文件中,使用您要使用其他命名空间的方法创建第二个源文件
// MyWebServiceClass.usingMethods.cs using ReportService2005; public partial class MyWebServiceClass { // methods... }
不幸的是不是 没有这样的语法来满足这种需求。
如果重叠的类是相同的(不只是命名相同)并共享相同的XML命名空间等,那么您可以利用wsdl.exe工具的sharetypesfunction来生成两个Web服务代理,以便它们为那些重叠的类共享相同的类型定义。
http://msdn.microsoft.com/en-us/library/7h3ystb6%28VS.80%29.aspx
查看“/ sharetypes”选项,看看它是否适用于您的情况。
虽然与使用命名空间或C#无关,但VB.NET支持With
关键字,可用作访问对象成员的快捷方式:
SomeReallyLongName.Property1 = 1 SomeReallyLongName.Property2 = 2 SomeReallyLongName.Property3 = 3 SomeReallyLongName.Property4 = 4 SomeReallyLongName.Property5 = 5
可以改写为:
With SomeReallyLongName .Property1 = 1 .Property2 = 2 .Property3 = 3 .Property4 = 4 .Property5 = 5 End With
它不在C#中,因为您可以使用其他方法非常接近相同的行为:
- 使用较短的变量名称
- 使用import-aliasing(如Martin建议)
AFAIK无法做到