简体   繁体   中英

Construct anonymous object from string, and enumerate through it's properties with reflection

So Basically I have this string which looks like query string "key1=value1&key2=value2" (or maybe JSON I have not decided it yet). so basically I want to convert this string Into an object and then enumerate through its properties (or fields) with reflection. I have already seen something called ExpandoObject but in my case that won't help out, because I cannot enumerate through it's properties, and by that I mean the my properties, like .Key1 and .Key2 (from the string above) with reflection (or may be It is possible and I am doing something wrong). Anyway, any help and suggestion would be appreciated.

EDIT:

the Thing i want to achieve is this. I have an object than I need to store that object in db some have, as a string I gave example above and after that I need to recreate that object again from that string. (just to have the same properties of fields that the object I saved had)

So I have this one method which can be called directly or indirectly. If I call it directly I can create the object which is passed to this method ( SomeParamsObject ) set it's propertioes and than pass it to the method, If called indirectly I am passing some other object to the other method which is calling that final method. to the first method I am passing some other objects and plus one anonymus object whichs properties are then merged with SomeParamsObject (create inside of the first method by some other objects passed to it) and is passed to the final method. I also need to store this anonymus object somewhere in DB because the call may repeat from the other module of the code, so that's why I need to reconstruct it, To change all this to some KeyValue collection, it would probably take me 4-5 days because this method is really called from bunch of modules of my code.

Can't you use a dictionary, or a NameValueCollection instead ?

var values = new NameValueCollection();
var pairs = "key1=value1&key2=value2".Split('&');
foreach(var kvp in pairs)
{
    var parts = kvp.Split('=');
    values.Add(parts[0], parts[1]);
}

Then you can access your values with keys:

var value1 = values["key1"];

Use HttpUtility.ParseQueryString method to create a NameValueCollection out of a query string.

var collection = HttpUtility.ParseQueryString("key1=value1&key2=value2");
foreach (string key in collection)
{
    string value = collection.Get(key);
    //Do whatever with key and value
}

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