简体   繁体   English

如何在C#中获取动态类型数组的成员?

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

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. 我在这里使用WSProxy类程序中动态调用Web服务,并且需要将返回的对象解析为XML,或者至少访问返回的Web服务结果内的成员。

For example, if I receive an Array of StateCodes, I need to do: 例如,如果我收到一个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);

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. 我正在使用刚刚开始学习的C#3.5。 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. 如果这个问题令人困惑,那是因为我很困惑。

Try casting it to IEnumerable . 尝试将其强制转换为IEnumerable

var goodResult = result as IEnumerable;

if (goodResult != null) // use it

Try casting it to IEnumerable 尝试将其转换为IEnumerable

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM