Casting Text Data to Members in a Businees Object via Reflection
I have a pipe-delimited text file that I am parsing and using to fill a collection
of custom business objects. Instead of hard-coding the bits of each pipe-delimited
line, I am using an XML file to map data items in the file to object members, like
this XML fragment:
<Field>
<Name>NAMID</Name>
<Location>0</Location>
<MapsTo>MemberId</MapsTo>
<IsRole>false</IsRole>
</Field>
After parsing and matching the data element to the proper member name, I call this
function:
public void SetDataMemberValue(string memberName, Member member, string data)
{
// get an instance
// of that object's type.
Type objectType = member.GetType();
PropertyInfo[] properties = objectType.GetProperties();
foreach (PropertyInfo property in properties)
{
if (string.Equals(property.Name, memberName, StringComparison.OrdinalIgnoreCase))
{
object[] args = new object[1];
args[0] = data;
object result = null;
if (property.PropertyType == data.GetType())
{
//The type of the property matches the data's type
result = data;
}
else
{
result = property.PropertyType.InvokeMember("Parse", BindingFlags.InvokeMethod, null, result, args);
}
if (result != null)
{
property.SetValue(member, result, null);
}
}
}
}
The tricky bit is the InvokeMember call, which is casting my string to the
appropriate type for the property. Of course this is they stylized version of the
function, I removed the try-catch bits to make it smaller and readable for the acutal
function. You should wrap the InvokeMember call with a try-catch as Parse
methods can fail quite hard.