本系列探討 WCF 如何在契約層面實現 OO 語意:
OperationContract(Name=...) 映射同名方法。
BasicWhetherInfo、WindInfo 及 Enum[DataContract] [KnownType(typeof(WhetherConditions))]
public class BasicWhetherInfo
{
[DataMember] public WhetherConditions Condition { get; set; }
[DataMember] public double Temperature { get; set; }
public override string ToString() => $"Conditions: {Condition}; Temperature: {Temperature}";
}
public enum WhetherConditions { Clear, Cloudy, Overcast, Rainy }
[DataContract] [KnownType(typeof(WindDirection))]
public class WindInfo
{
[DataMember] public WindDirection Direction { get; set; }
[DataMember] public string Speed { get; set; }
public override string ToString() => $"Direction: {Direction}; Speed: {Speed}";
}
public enum WindDirection { East, South, West, North, Northeast, Southeast, Northwest, Southwest }
[ServiceContract]
public interface ISimpleWhetherForecast
{
[OperationContract] BasicWhetherInfo GetBasicWhetherInfo(string postalcode);
}
[ServiceContract]
public interface IFullWhetherForecast : ISimpleWhetherForecast
{
[OperationContract] WindInfo GetWindInfo(string postalcode);
}
關鍵點:ServiceContractAttribute 的 Inherited=false,故子介面必須重新標註 [ServiceContract]。
public class SimpleWhetherForecastService : ISimpleWhetherForecast
{
public BasicWhetherInfo GetBasicWhetherInfo(string postalcode)
=> new BasicWhetherInfo(WhetherConditions.Overcast, 23);
}
public class FullWhetherForecastService : SimpleWhetherForecastService, IFullWhetherForecast
{
public WindInfo GetWindInfo(string postalcode)
=> new WindInfo(WindDirection.Northwest, "12km/h");
}
實作類別繼承實現 GetBasicWhetherInfo 邏輯複用,符合 DRY 原則。
<%@ ServiceHost Service="Artech.InheritanceHierarchy.Service.FullWhetherForecastService, Artech.InheritanceHierarchy.Service" %>
// Web.config 端點繫結至最底層 Contract
<endpoint contract="Artech.InheritanceHierarchy.Service.IFullWhetherForecast" binding="wsHttpBinding" />
Part II 將示範如何在 客戶端 重建相同繼承架構,而非接受扁平化 Proxy,達成端到端 OO 體驗。