public static void SetSpecifiedPropertyValueByName(object targetObject, string propertyName, object value)
{
if (string.IsNullOrEmpty(propertyName) || null == value || null == targetObject)
{
return;
}
PropertyInfo matchedProperty = targetObject.GetType().GetProperty(propertyName);
if (matchedProperty != null)
{
if (matchedProperty.PropertyType == typeof(DateTime?))
{
value = DateTime.Parse(value.ToString());
}
else if (matchedProperty.PropertyType == typeof(byte) || matchedProperty.PropertyType == typeof(byte?))
{
value = byte.Parse(value.ToString());
}
else if (matchedProperty.PropertyType == typeof(bool) || matchedProperty.PropertyType == typeof(bool?))
{
if (value.ToString() == "0")
{
value = false;
}
else if (value.ToString() == "1")
{
value = true;
}
else
{
value = bool.Parse(value.ToString());
}
}
else if (matchedProperty.PropertyType == typeof(uint) || matchedProperty.PropertyType == typeof(uint?))
{
value = uint.Parse(value.ToString());
}
else if (matchedProperty.PropertyType == typeof(int) || matchedProperty.PropertyType == typeof(int?))
{
value = int.Parse(value.ToString());
}
else if (matchedProperty.PropertyType == typeof(ushort) || matchedProperty.PropertyType == typeof(ushort?))
{
value = ushort.Parse(value.ToString());
}
matchedProperty.SetValue(targetObject, value, null);
}
}