如何在没有新类名的情况下扩展 System.Web.Services.WebService?
我尝试过以几种不同的形式来做到这一点,这只是最近的一种。我通常会笨手笨脚地几个小时,却一事无成,所以我想用我的现实世界的例子来提出这个问题。
我有一个 Web 服务,我可以从中编写 XML,以便人们可以从我们的服务器中提取信息,所以我有:
(namespace)
public static class WebServices
{
public static void WriteXML(this WebService svc, DataSet results)
{
if (results != null)
HttpContext.Current.Response.Write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?><xsl:stylesheet version=\"1.0\" " +
"xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns=\"http://www.w3.org/1999/xhtml\">" + results.GetXml() + "</xsl:stylesheet>");
}
}
不幸的是,这只能进行以下操作:
using (namespace)
....
this.WriteXML(DataSet);
当我想
using (namespace)
....
WriteXML(DataSet);
要这样做时,我缺少什么?
I've tried to do this in several different forms and this is just the most recent. I usually bumble for several hours and never get anywhere so I'd like to put the question out here with my real-world example.
I have Web Services which I write XML from so that people can pull information from our server, so I have:
(namespace)
public static class WebServices
{
public static void WriteXML(this WebService svc, DataSet results)
{
if (results != null)
HttpContext.Current.Response.Write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?><xsl:stylesheet version=\"1.0\" " +
"xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns=\"http://www.w3.org/1999/xhtml\">" + results.GetXml() + "</xsl:stylesheet>");
}
}
Unforunately, that's only accessible doing:
using (namespace)
....
this.WriteXML(DataSet);
When I want
using (namespace)
....
WriteXML(DataSet);
What am I missing to do so?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您为
WebService
编写了一个扩展方法 - 您的第一个参数是this WebService svc
,这意味着您的扩展方法WriteXML
只能在WebService
的实例。you wrote an extension method for
WebService
- your first parameter isthis WebService svc
which in turn means that your extension methodWriteXML
can only be called on an instance ofWebService
.如果它是一个部分类,那么您可以添加一个方法,但在 MSDN 文档中它并没有说它是部分的。您必须使用扩展方法来扩展它,并且必须使用
this
关键字来访问它。五个额外的角色对我来说似乎并不算太糟糕。您不想使用该关键字还有其他原因吗?You could get away with being able to add a method if it were a partial class but in the MSDN docs it doesn't say it's partial. You have to extend it with extension methods and have to use the
this
keyword to access it. Five extra characters doesn't seem too bad to me. Is there another reason why you don't want to use the keyword?您可以将该方法放入基类中,然后从基类派生所有 Web 服务。基类将从 WebService 派生。
顺便说一句,除非您使用
WebService
类的成员,否则根本不需要从它派生。您可以简单地使用[WebService]
装饰您的 Web 服务类。You can place that method into a base class, then derive all of your web services from the base class. The base class will derive from WebService.
BTW, unless you use the members of the
WebService
class, you don't need to derive from it at all. You can simply decorate your web service classes with[WebService]
.