简体   繁体   中英

Accessing elements in a dynamic object in C#

I have a public function which returns a dynamic object. Such dynamic object is actually of type MyObj where MyObj is a private class of the class which contains the function.

public class MyClass
{
        private class MyElement
        {
            public string myString{ get; set; }
        }

        private class MyObj
        {
            public List<MyElement> data { get; set; }
        }

        public dynamic myMethod()
        {
            List<MyElement> myList = (some complex code here).ToList();
            var myObj = new MyObj{ data = myList };

            return myObj;
        }
}

Now I need to call such function from outside the class like this:

var c = new MyClass();
var stuff = c.myMethod();

and traverse the element of the output object but as you can see the stuff object is shaped as a dynamic (look at the return type of the function) so I don'y know the type (is private). How can I explore the array?

I'll try to answer your question, though what you are trying to achieve is a little bit odd.

First thing: you can't access properties of dynamic object if the class of this object is private as metadata of the object is not exposed to you.

The only way is to use reflection:

var myClass = new MyClass();
var stuff = myClass.myMethod();
var dynamicType = (TypeInfo)stuff.GetType();

var dataProperty = dynamicType.GetProperty("data");
var data = (IEnumerable)dataProperty.GetValue(stuff);

var result = new List<string>();
Type itemType = null;
PropertyInfo myProperty = null;
foreach(var item in data){
    if(itemType == null){
        itemType = item.GetType();
        myProperty = itemType.GetProperty("myString");
    }

    var content = (string)myProperty.GetValue(item);
    result.Add(content);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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