How do I get members of a dynamically typed array in C#?

戏子无情 提交于 2019-12-25 08:47:35

问题


I'm dynamically calling web services in my program using the WSProxy class here, and I need to parse the returned object to XML, or at least access the members inside the returned web service result.

For example, if I receive an Array of StateCodes, I need to do:

 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);

I've tried various methods to get to array members, but I'm hitting a dead end.

        // 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)

Since I won't know the type of the array which is returned beforehand, I can't do early binding. I'm using C# 3.5, which I've just started learning. I keep hearing "reflection" coming up, but the examples I've read don't seem to apply to this question.

If this question is confusing, it's because I'm very confused.


回答1:


Try casting it to IEnumerable

var list = result as IEnumerable;
if(list != null) 
{
   foreach (var i in list)
   {
       // Do stuff
   }
}



回答2:


Try casting it to IEnumerable.

var goodResult = result as IEnumerable;

if (goodResult != null) // use it


来源:https://stackoverflow.com/questions/4157191/how-do-i-get-members-of-a-dynamically-typed-array-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!