如何:在 Web 服务中使用继承
下面的代码示例演示如何使用继承来创建执行数学计算的 Web 服务。 此示例阐释了使用 ASP.NET 创建的 XML Web services 的设计准则主题中阐述的准则之一。
示例
<%@ WebService Language="C#" Class="Add" %>
using System;
using System.Web.Services;
abstract public class MathService : WebService
{
[WebMethod]
abstract public float CalculateTotal(float a, float b);
}
public class Add : MathService
{
[WebMethod]
override public float CalculateTotal(float a, float b)
{
return a + b;
}
}
public class Subtract : MathService
{
[WebMethod]
override public float CalculateTotal(float a, float b)
{
return a - b;
}
}
public class Multiply : MathService
{
[WebMethod]
override public float CalculateTotal(float a, float b)
{
return a * b;
}
}
public class Divide : MathService
{
[WebMethod]
override public float CalculateTotal(float a, float b)
{
if (b==0)
return -1;
else
return a / b;
}
}
<%@ WebService Language="VB" Class="Add" %>
Imports System
Imports System.Web.Services
MustInherit Public Class MathService : Inherits WebService
<WebMethod> _
Public MustOverride Function CalculateTotal(a As Single, _
b As Single) As Single
End Class
Public Class Add : Inherits MathService
<WebMethod> _
Public Overrides Function CalculateTotal(a As Single, _
b As Single) As Single
Return a + b
End Function
End Class
Public Class Subtract : Inherits MathService
<WebMethod> _
Public Overrides Function CalculateTotal(a As Single, _
b As Single) As Single
Return a - b
End Function
End Class
Public Class Multiply : Inherits MathService
<WebMethod> _
Public Overrides Function CalculateTotal(a As Single, _
b As Single) As Single
Return a * b
End Function
End Class
Public Class Divide : Inherits MathService
<WebMethod> _
Public Overrides Function CalculateTotal(a As Single, _
b As Single) As Single
If b = 0 Then
Return - 1
Else
Return a / b
End If
End Function
End Class
请参见
概念
使用 ASP.NET 创建的 XML Web services 的设计准则
版权所有 (C) 2007 Microsoft Corporation。保留所有权利。