Note that there are some explanatory texts on larger screens.

plurals
  1. POStoring a property of the type specified in a string
    text
    copied!<p>There's an XML scheme which says something like this:</p> <pre><code>&lt;ExtraFields&gt; &lt;ExtraField Type="Int"&gt; &lt;Key&gt;Mileage&lt;/Key&gt; &lt;Value&gt;500000 &lt;/Value&gt; &lt;/ExtraField&gt; &lt;ExtraField Type="String"&gt; &lt;Key&gt;CarModel&lt;/Key&gt; &lt;Value&gt;BMW&lt;/Value&gt; &lt;/ExtraField&gt; &lt;ExtraField Type="Bool"&gt; &lt;Key&gt;HasAbs&lt;/Key&gt; &lt;Value&gt;True&lt;/Value&gt; &lt;/ExtraField&gt; &lt;/ExtraFields&gt; </code></pre> <p>I want to store this info in the class and I want its field to be of the specified type. I thought of a generic approach</p> <pre><code> static class Consts { public const string Int32Type = "int32"; public const string StringType = "string"; public const string BoolType = "bool"; } public class ExtraFieldValue&lt;TValue&gt; { public string Key; public TValue Value;public static ExtraFieldValue&lt;TValue&gt; CreateExtraField(string strType, string strValue, string strKey) { IDictionary&lt;string, Func&lt;string, object&gt;&gt; valueConvertors = new Dictionary&lt;string, Func&lt;string, object&gt;&gt; { { Consts.Int32Type, value =&gt; Convert.ToInt32(value)}, { Consts.StringType, value =&gt; Convert.ToString(value)}, { Consts.BoolType, value =&gt; Convert.ToBoolean(value)} }; if (!valueConvertors.ContainsKey(strType)) return null; ExtraFieldValue&lt;TValue&gt; result = new ExtraFieldValue&lt;TValue&gt; { Key = strKey, Value = (TValue)valueConvertors[strType](strValue) }; return result; } } </code></pre> <p>But the problem with this approach is that I need a list of ExtraFields and each of them can have different type in a list.</p> <p>I can only think of two options so far:</p> <p>1) using a dynamic keyword for this field but this approach seems to have limits</p> <p>2) using an object type for the field and casting its dynamic type to the necessary type. But anyhow if I will need some object specific calls, I will have to make a static cast.</p> <p>I would be glad to read your thoughts/proposals</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload