共用方式為


HOW TO:在 Web 服務中使用繼承

下列程式碼範例將示範如何使用繼承來建立執行數學計算的 Web 服務。此範例說明使用 ASP.NET 建立之 XML Web Service 的設計方針主題所解釋的其中一項方針。

範例

<%@ 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 Service 的設計方針

Footer image

Copyright © 2007 by Microsoft Corporation. All rights reserved.