mirror of
https://github.com/ICDSystems/ICD.Common.Utils.git
synced 2026-02-09 09:45:10 +00:00
docs: Better exception messages when failing to convert type
This commit is contained in:
@@ -195,6 +195,24 @@ namespace ICD.Common.Utils
|
||||
!= null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Platform independant delegate instantiation.
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <param name="firstArgument"></param>
|
||||
/// <param name="method"></param>
|
||||
/// <returns></returns>
|
||||
public static Delegate CreateDelegate(Type type, object firstArgument, MethodInfo method)
|
||||
{
|
||||
return
|
||||
#if SIMPLSHARP
|
||||
CDelegate
|
||||
#else
|
||||
Delegate
|
||||
#endif
|
||||
.CreateDelegate(type, firstArgument, method);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an instance of the given type, calling the default constructor.
|
||||
/// </summary>
|
||||
@@ -368,42 +386,33 @@ namespace ICD.Common.Utils
|
||||
if (type.CanBeNull())
|
||||
return null;
|
||||
|
||||
throw new InvalidCastException();
|
||||
throw new InvalidCastException(string.Format("Unable to convert NULL to type {0}", type.Name));
|
||||
}
|
||||
|
||||
Type valueType = value.GetType();
|
||||
if (valueType.IsAssignableTo(type))
|
||||
return value;
|
||||
|
||||
// Handle enum
|
||||
if (type.IsEnum)
|
||||
try
|
||||
{
|
||||
if (valueType.IsIntegerNumeric())
|
||||
return Enum.ToObject(type, 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);
|
||||
if (value is string)
|
||||
return Enum.Parse(type, value as string, false);
|
||||
}
|
||||
|
||||
return Convert.ChangeType(value, type, null);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
string valueString = valueType.ToString();
|
||||
string message = string.Format("Failed to convert {0} to type {1} - {2}", valueString, type, e.Message);
|
||||
throw new InvalidCastException(message, e);
|
||||
}
|
||||
|
||||
return Convert.ChangeType(value, type, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Platform independant delegate instantiation.
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <param name="firstArgument"></param>
|
||||
/// <param name="method"></param>
|
||||
/// <returns></returns>
|
||||
public static Delegate CreateDelegate(Type type, object firstArgument, MethodInfo method)
|
||||
{
|
||||
return
|
||||
#if SIMPLSHARP
|
||||
CDelegate
|
||||
#else
|
||||
Delegate
|
||||
#endif
|
||||
.CreateDelegate(type, firstArgument, method);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user