如何获得C#中的动态类型数组的成员? [英] How do I get members of a dynamically typed array in C#?

查看:474
本文介绍了如何获得C#中的动态类型数组的成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的程序中使用WSProxy类动态调用Web服务这里,我需要将返回的对象解析为XML,或至少访问返回的Web服务结果中的成员。

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.

例如,如果我收到一个StateCodes数组,我需要:

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)

由于我不知道事先返回的数组的类型,我不能做早期绑定。我使用C#3.5,我刚刚开始学习。我不断听到反思,但我看过的例子似乎不适用于这个问题。

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.

推荐答案

尝试将其转换为IEnumerable

Try casting it to IEnumerable

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

这篇关于如何获得C#中的动态类型数组的成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆