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 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 時要設public ArrayList GetData ( ) {
ArrayList ar = new ArrayList ( );
CompositeType c = new CompositeType ( );
c.StringValue = "aaa";
ar.Add ( c );
return ar;
}
}
Client
ServiceReference1.ServiceClient c = new ServiceReference1.ServiceClient ( );
ArrayList ar = ( ArrayList ) c.GetData ( );
Console.WriteLine ( (( CompositeType ) ar [ 0 ]).StringValue.ToString() );
ArrayList ar = ( ArrayList ) c.GetData ( );
Console.WriteLine ( (( CompositeType ) ar [ 0 ]).StringValue.ToString() );
沒有留言:
張貼留言