c# - Storing a property of the type specified in a string -


there's xml scheme says this:

<extrafields>   <extrafield type="int">    <key>mileage</key>    <value>500000 </value>   </extrafield>   <extrafield type="string">    <key>carmodel</key>    <value>bmw</value>   </extrafield>   <extrafield type="bool">    <key>hasabs</key>    <value>true</value>   </extrafield>     </extrafields> 

i want store info in class , want field of specified type. thought of generic approach

     static class consts {     public const string int32type = "int32";     public const string stringtype = "string";     public const string booltype = "bool"; }  public class extrafieldvalue<tvalue> {     public string key;     public tvalue value;public static extrafieldvalue<tvalue> createextrafield(string strtype, string strvalue, string strkey)     {         idictionary<string, func<string, object>> valueconvertors = new dictionary<string, func<string, object>> {                   { consts.int32type, value => convert.toint32(value)},                   { consts.stringtype, value => convert.tostring(value)},                   { consts.booltype, value => convert.toboolean(value)}         };          if (!valueconvertors.containskey(strtype))             return null;          extrafieldvalue<tvalue> result = new extrafieldvalue<tvalue>         {             key = strkey,             value = (tvalue)valueconvertors[strtype](strvalue)         };          return result;     }  } 

but problem approach need list of extrafields , each of them can have different type in list.

i can think of 2 options far:

1) using dynamic keyword field approach seems have limits

2) using object type field , casting dynamic type necessary type. anyhow if need object specific calls, have make static cast.

i glad read thoughts/proposals

just use name/value collection. if don't know property names until runtime, using dynamic, or dynamically building type @ runtime isn't going because won't able write source accesses properties.

so, use name/value collection implements idictionary<string, object>.


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -