mirror of
https://github.com/ICDSystems/ICD.Common.Utils.git
synced 2026-02-14 04:05:04 +00:00
feat: ChangeType util method for converting a value to a given type
This commit is contained in:
@@ -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)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user