WCF 序列化需知曉具體型別。基類 Employee、子類 Intern,Client 傳 Intern 給期望 Employee 的操作會失敗 (服務端無法反序列化)。
在基類標註子類:
[DataContract]
[KnownType(typeof(Intern))]
public class Employee { ... }
缺點:作用域過廣,所有使用此資料契約的操作皆受影響,無法針對特定操作限制。
可標註於 介面、方法、類別,精確控制範圍。
[ServiceContract]
public interface IEmployeeManage {
[OperationContract]
[ServiceKnownType(typeof(Intern))]
void AddEmployee(Employee employee);
[OperationContract]
[ServiceKnownType(typeof(Intern))]
Employee GetEmployee();
}
或在服務契約類別層級:[ServiceKnownType(typeof(Intern))] public interface IEmployeeManage { ... },套用所有操作。
資料契約只能標註 Class/Struct,但基底可以是介面。須在服務契約以 ServiceKnownType 指定具體實作類別:
interface IEmployee { ... }
[DataContract] class Intern : IEmployee { ... }
[ServiceContract]
[ServiceKnownType(typeof(Intern))]
interface IEmployeeManage {
[OperationContract] void AddEmployee(IEmployee employee);
}
不可將 KnownType 標註於介面,因中繼資料不包含介面定義。