Dieses Snippet bietet eine einfache Möglichkeit eine generische Konvertierung in ein Zieltyp zu ermöglichen. Voraussetzung ist, dass der Zieltyp das IConvertible Interface implementiert hat.
/// <summary>
/// Static helper method to do a generic conversion.
/// </summary>
/// <typeparam name="T">Source object type.</typeparam>
/// <typeparam name="L">Destination object tpye.</typeparam>
/// <param name="sourceObject">The source object (value).</param>
/// <param name="throwError">If set to true, conversion errors results in Exception, otherwise no exception will be thrown.</param>
/// <param name="destination">The destination object (value).</param>
/// <returns>True, after succesful conversion otherwise false.</returns>
public static bool GetValueFromGeneric<T, L>(L sourceObject, bool throwError, out T destination)
where T : IConvertible
{
// locale variables
bool retVal = false;
destination = default(T);
// do the conversion
try
{
destination = (T)Convert.ChangeType(sourceObject, typeof(T));
retVal = true;
}
catch
{
if (throwError)
{
throw;
}
retVal = false;
}
return retVal;
}
Kommentare zum Snippet