如何使用KnownType 在WCF 服务合同中启用多态返回值? [英] How do I use KnownType to enable polymorphic return values in a WCF service contract?
问题描述
我正在将远程接口转换为 WCF,但是我有一个方法声明为返回对象"并且可以返回许多不同的类型(主要是不同的枚举)
I am converting a remoting interface to WCF, however I have a method that is declared to return "object" and can return a number of different types (mostly different enums)
在哪里可以找到应对此问题的示例?
Where can I find an example of coping with this?
(我正在使用包含所有类型的共享合约程序集,而不是生成客户端代理,如果这有所不同.)
(I am using a shared contract assembly that contains all the types rather than generating a client proxy if that makes a difference.)
推荐答案
这就是我最后所做的,但是我很高兴开始使用 Aaron Fischer 长期提供的解决方案之一.
This is what I did in the end, however I am lickly to start using one of the soltuions that Aaron Fischer gave in the long term.
/// <summary>
/// WCF can not cope with a method that returns an object so wrap the
/// untyped object in a typed object. Then use KnowType to tell WCF
/// about the typs that are wrapped
/// </summary>
[DataContract(), KnownType(typeof(MyType1)), KnownType(typeof(MyType2))]
public class UntypedObjectHolder
{
[DataMember()]
private object m_Value;
public UntypedObjectHolder(object value)
{
m_Value = value;
}
public object Value
{
get { return m_Value; }
}
}
然后在我的界面中
[OperationContract()]
UntypedObjectHolder GetValue(eGetValueType valueType);
<小时>
我没有尝试过的另一个可能有效的选项是
Another option that may work that I did not try is
[ServiceContract]
[ServiceKnownType(typeof(PhotoCamera))]
[ServiceKnownType(typeof(TemperatureSensor))]
[ServiceKnownType(typeof(DeviceBase))]
public interface IHomeService
{
[OperationContract] IDevice GetInterface();
}
这篇关于如何使用KnownType 在WCF 服务合同中启用多态返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!