c# - Convert String Into Dynamic Object -


is there straightforward way of converting:

string str = "a=1,b=2,c=3"; 

into:

dynamic d = new { = 1, b = 2, c = 3 }; 

i think write function splits string , loops results create dynamic object. wondering if there more elegant way of doing this.

you may use microsoft roslyn (here's all-in-one nuget package):

class program {     static void main(string[] args)     {         string str = "a=1,b=2,c=3,d=\"4=four\"";         string script = string.format("new {{ {0} }}",str);         var engine = new scriptengine();         dynamic d = engine.createsession().execute(script);     } } 

and if want add more complex types:

string str = "a=1,b=2,c=3,d=\"4=four\",e=guid.newguid()"; ... engine.addreference(typeof(system.guid).assembly); engine.importnamespace("system"); ... dynamic d = engine.createsession().execute(script); 

based on question in comment, there code injection vulnerabilities. add system reference , namespace shown right above, replace str with:

string str =     @" a=1, oops = (new func<int>(() => {                  console.writeline(                     ""security incident!!! user {0}\\{1} exposed "",                     environment.userdomainname,                     environment.username);                  return 1;              })).invoke() "; 

Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -

c# - String.format() DateTime With Arabic culture -