feat: ChangeType util method for converting a value to a given type

This commit is contained in:
Chris Cameron
2018-04-05 11:27:27 -04:00
parent 007663a193
commit 26107887f1
2 changed files with 62 additions and 1 deletions

View File

@@ -121,9 +121,33 @@ namespace ICD.Common.Utils.Tests
}
[Test]
public void LoadAssemblyFromPath()
public void LoadAssemblyFromPathTest()
{
Assert.Inconclusive();
}
[Test]
public void GetImplementationTest()
{
Assert.Inconclusive();
}
[Test]
public void ChangeTypeTest()
{
// Same type
Assert.AreEqual(10, ReflectionUtils.ChangeType(10, typeof(int)));
// Null
Assert.AreEqual(null, ReflectionUtils.ChangeType(null, typeof(string)));
// Enums
Assert.AreEqual(BindingFlags.GetProperty, ReflectionUtils.ChangeType((int)(object)BindingFlags.GetProperty, typeof(BindingFlags)));
Assert.AreEqual(BindingFlags.GetProperty, ReflectionUtils.ChangeType(BindingFlags.GetProperty.ToString(), typeof(BindingFlags)));
Assert.AreEqual(BindingFlags.GetProperty, ReflectionUtils.ChangeType(((int)(object)BindingFlags.GetProperty).ToString(), typeof(BindingFlags)));
// Everything else
Assert.AreEqual(10, ReflectionUtils.ChangeType("10", typeof(int)));
}
}
}

View File

@@ -368,5 +368,42 @@ namespace ICD.Common.Utils
? property
: GetImplementation(property.DeclaringType, property);
}
/// <summary>
/// Changes the given value to the given type.
/// </summary>
/// <param name="value"></param>
/// <param name="type"></param>
/// <returns></returns>
public static object ChangeType(object value, Type type)
{
if (type == null)
throw new ArgumentNullException("type");
// Handle null value
if (value == null)
{
if (type.CanBeNull())
return null;
throw new InvalidCastException();
}
Type valueType = value.GetType();
if (valueType.IsAssignableTo(type))
return value;
// Handle enum
if (type.IsEnum)
{
if (valueType.IsIntegerNumeric())
return Enum.ToObject(type, value);
if (value is string)
return Enum.Parse(type, value as string, false);
}
return Convert.ChangeType(value, type, null);
}
}
}