Тормозит try catch при ошибке Convert - C#
Формулировка задачи:
Поясню давно использую такую вот универсальную функцию для конвертирования данных
Она работает хорошо и удачно позволят обрабатывать ситуации когда пользователь ввел что попало в некритичное поле или реагировать на ситуацию когда из базы пришла какая нибудь неведома-зверушка. Но есть проблема при больших объемах неконвертируемых данных (когда часто падает на catch ) эта конструкция начинает тормозить не по детски. вот собственно вопрос есть ли способ переделать это на конструкцию if/else возможно у Convert есть метод на подобие isConvertable ?
Заранее благодарен за любые советы по оптимизации этой функции.
public static T ConvertTo<T>(object o, T def = default(T))
{
try
{
return (T)Convert.ChangeType(o, typeof(T));
}
catch (Exception)
{
return def;
}
}Решение задачи: «Тормозит try catch при ошибке Convert»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace ConsoleApplication21
{
class Program
{
static void Main(string[] args)
{
var b = 34;
var c = ConvertToValue<double>(b);
Console.WriteLine(c.GetType());
Console.ReadKey();
}
public static T ConvertToValue<T>(object o, T def = default(T)) where T : struct
{
var type = typeof(T);
if (o.GetType().IsCastableTo(type)) return (T)Convert.ChangeType(o, typeof(T));
else return def;
}
}
static class TypeExtensions
{
static Dictionary<Type, List<Type>> dict = new Dictionary<Type, List<Type>>() {
{ typeof(decimal), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(char) } },
{ typeof(double), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(char), typeof(float) } },
{ typeof(float), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(char), typeof(float) } },
{ typeof(ulong), new List<Type> { typeof(byte), typeof(ushort), typeof(uint), typeof(char) } },
{ typeof(long), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(char) } },
{ typeof(uint), new List<Type> { typeof(byte), typeof(ushort), typeof(char) } },
{ typeof(int), new List<Type> { typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(char) } },
{ typeof(ushort), new List<Type> { typeof(byte), typeof(char) } },
{ typeof(short), new List<Type> { typeof(byte) } }
};
public static bool IsCastableTo(this Type from, Type to)
{
if (to.IsAssignableFrom(from)) return true;
if (dict.ContainsKey(to) && dict[to].Contains(from)) return true;
return from.GetMethods(BindingFlags.Public | BindingFlags.Static).Any(m => m.ReturnType == to && (m.Name == "op_Implicit" || m.Name == "op_Explicit"));
}
}
}