我需要將一些與Silverlight不兼容的對象轉換爲通過WCF服務發送的模型。我試過使用ServiceKnownType,但結果仍然是對象。我可以在檢索結果後將對象投射到模型上,但我不想每次都這樣做。這是我嘗試過的一個例子。WCF服務和接口 - 結果是對象,儘管使用了ServiceKnownType
這是一個很好的方法嗎?爲什麼WCF不會將BikeModel作爲對象返回。
接口
public interface IBike
{
string BikeName { get; set;}
}
模型
[DataContract]
public class BikeModel : IBike
{
[DataMember]
public string BikeName { get; set; }
}
不能在因爲MarshalObjectByRef等的Silverlight中的基類可以使用其他對象
public class Bike : IBike, UnusableBaseClass
{
....
}
IService1
[ServiceContract]
[ServiceKnownType(typeof(BikeModel))]
public interface IService1
{
[OperationContract]
IBike GetBike();
}
服務
public class Service1 : IService1
{
public IBike GetBike()
{
Bike b = BikeManager.GetFirstBikeInTheDataBase();
return b;
}
}
MainPage.xaml.cs中 -
public MainPage()
{
InitializeComponent();
this.Loaded += (s, a) =>
{
ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
client.GetBikeCompleted += (sender, e) =>
{
var d = e.Result;
// this cast works
BikeModel model = (BikeModel)d;
};
client.GetBikeAsync();
};
}
我剛剛檢查了我的代碼,它是DataContract,所以它是一個錯字。我編輯了我的帖子來解決它。謝謝。 – Aligned 2010-05-11 20:28:26
更改爲基本類型導致服務返回BaseBikeModel的結果。不幸的是,由於需求等原因,我無法更改Bike對象的基類。 我試圖將[KnownType(typeof(IBike))]放在BikeModel上,並沒有任何運氣。你是對的WCF並不總是按照人們所期望的方式工作。 – Aligned 2010-05-11 20:59:32
@Kevin:對不起,我的意思是嘗試將[KnownType(typeof(BikeModel))]放到返回IBike的操作上。它已經返回了IBike - 所以你不需要再把它作爲一個額外的「已知類型」 – 2010-05-12 04:59:42