2011年4月19日 星期二

Q&A 從WCF回傳ArrayList與自訂型別

收到李先生問題如下:
Q :
我的 WCF Service 需回傳 ArrayList,
若 ArrayList 只內含一些 string, 程式可 work,
但 ArrayList 若內含一些 Custom Class 就不 work,
請問老師問題出在那兒 ?
A:
善用DataContract與ServiceKnownType Attribute就可以囉~
例如Service Contract為:
[ServiceContract]
public interface IService {
    [OperationContract]
   [ServiceKnownType ( typeof ( CompositeType ) )]     ArrayList GetData ( );
}
[DataContract] public class CompositeType {
    bool boolValue = true;
    string stringValue = "Hello ";
    [DataMember]
    public bool BoolValue {
        get { return boolValue; }
        set { boolValue = value; }
    }
    [DataMember]
    public string StringValue {
        get { return stringValue; }
        set { stringValue = value; }
    }
}
服務:
public class Service : IService {
    public ArrayList GetData ( ) {
        ArrayList ar = new ArrayList ( );
        CompositeType c = new CompositeType ( );
        c.StringValue = "aaa";
        ar.Add ( c );
        return ar;
    }
}
產生Proxy 時要設
image
Client
ServiceReference1.ServiceClient c = new ServiceReference1.ServiceClient ( );
ArrayList ar = ( ArrayList ) c.GetData (  );
Console.WriteLine ( (( CompositeType ) ar [ 0 ]).StringValue.ToString() );

總網頁瀏覽量