我正在使用WSProxy类here在我的程序中动态调用Web服务,我需要将返回的对象解析为XML,或者至少访问返回的Web服务结果中的成员。
例如,如果我收到一个StateCodes数组,我需要这样做:
public object RunService(string webServiceAsmxUrl, string serviceName, string methodName, string jsonArgs)
{
WSDLRuntime.WsProxy wsp = new WSDLRuntime.WsProxy();
// Convert JSON to C# object.
JavaScriptSerializer jser = new JavaScriptSerializer();
var dict = jser.Deserialize<Dictionary<string,object>>(jsonArgs);
// uses mi.Invoke() from the WSProxy class, returns an object.
var result = wsp.CallWebService(webServiceAsmxUrl, serviceName, methodName, dict);
我已经尝试了各种方法来获取数组成员,但我已经走到了死胡同。
// THIS WON'T WORK.
// "Cannot apply indexing with [] to an expression of type 'object'"
var firstResult = result[0];
// THIS WON'T WORK.
// "foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'"
foreach (var i in result)
{
}
return object
//At the end of the class, if I try to return the object for XML parsing, I'll get this:
//System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: The type StateCodes[] may not be used in this context.
//at System.Xml.Serialization.XmlSerializationWriter.WriteTypedPrimitive(String name, String ns, Object o, Boolean xsiType)
由于我不知道事先返回的数组的类型,我不能做早期绑定。我正在使用C#3.5,我刚刚开始学习。我一直听到“反思”,但我读过的例子似乎并不适用于这个问题。
如果这个问题令人困惑,那是因为我很困惑。
答案 0 :(得分:1)
尝试将其投放到IEnumerable
。
var goodResult = result as IEnumerable;
if (goodResult != null) // use it
答案 1 :(得分:1)
尝试将其投射到IEnumerable
var list = result as IEnumerable;
if(list != null)
{
foreach (var i in list)
{
// Do stuff
}
}