Note that there are some explanatory texts on larger screens.

plurals
  1. POCan I use reflection and a string to get/set the correct property of an object?
    text
    copied!<p>I am using c# &amp; .NET 3.5. A vendor gives us an object that has properties of UserVarNbr1, UserVarData1, UserVarNbr2, UserVarData2,... UserVarNbrN, UserVarDataN. Not the way I would have coded it but nonetheless, this is what we have to work with. Another object in the application returns a collection of items used to represent these UserVariables.</p> <p>The collection items have properties like this</p> <pre><code>public string VariableName { get { return _VariableName; } set { _VariableName = value; } } public string VariableData { get { return _VariableData; } set { _VariableData = value; } } </code></pre> <p>I need to loop through the collection and create an instance of the vendor object and set the correct properties. UserVarNbrN, UserVarDataN needs to be put in the correct place. Note the collection returns a VariableName as a string "03", this needs to drive VendorObject properties UserVarNbr3, UserVarData3 **notice no "0" in the actual property name. How do I reference the correct property to get/set?</p> <pre><code>var o = new VendorObj(); </code></pre> <p>I have something like this so far. </p> <pre><code>foreach (var item in userVars) { const string propPrefix = "UserVar"; int varNum; var isNum = int.TryParse(item.VariableName, out varNum); if(isNum) { PropertyInfo pi; //this is where I am stuck // I need to set the corresponding properties on o // example if varNum == 38, how do I reference // o.(propPrefix+"Nbr"+varNum.ToString()) // and // o.(propPrefix+"Data"+varNum.ToString()) // so I may set them? } } </code></pre> <p>Any help is appreciated. I am a rookie when it come to reflection.</p> <p>Thanks, ~ck in San Diego</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