Created
November 30, 2011 03:39
-
-
Save Romiko/1407896 to your computer and use it in GitHub Desktop.
ConvertAndSetValue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.ComponentModel; | |
using System.Reflection; | |
namespace Romiko | |
{ | |
public static class ConverterExtensions | |
{ | |
public static void ConvertAndSetValue<TResult>(this TResult result, string value, PropertyInfo prop) where TResult : new() | |
{ | |
try | |
{ | |
var validType = prop.PropertyType; | |
if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) | |
{ | |
var nullableConverter = new NullableConverter(prop.PropertyType); | |
validType = nullableConverter.UnderlyingType; | |
} | |
if (value == null || string.IsNullOrEmpty(value)) | |
{ | |
prop.SetValue(result, null, null); | |
return; | |
} | |
object convertedData; | |
if (validType.IsEnum) | |
{ | |
convertedData = Enum.Parse(validType, value, false); | |
} | |
else if (validType == typeof(DateTimeOffset)) | |
{ | |
convertedData = DateTimeOffset.Parse(value); | |
} | |
else | |
{ | |
convertedData = Convert.ChangeType(value, validType); | |
} | |
prop.SetValue(result, convertedData, null); | |
} | |
catch (Exception ex) | |
{ | |
throw new Exception(string.Format("Could not set property {0} to value {1} for type {2}\n {3}", prop.Name, | |
value, result.GetType().FullName, ex)); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment