jeudi 29 janvier 2015

Invoke Func without knowing it's type at compile time

I'm trying to write something and I've hit a dead end. I have the following code :



public class ObjectConverter
{
private Dictionary<Type, object> m_Conversions = new Dictionary<Type, object>();

public void AddConversion<TOut>(Func<object, TOut> conversion)
{
m_Conversions[typeof(TOut)] = conversion;
}

public T Convert<T>(object value)
{
var conversion = (Func<object, T>) m_Conversions[typeof(T)];
return conversion(value);
}
}


It's a simplification of the real thing, but basically it allows to convert an object to any type for which we have defined a conversion. That way you can do stuff like :



// Intialization
converter.AddConversion(x => Convert.ToInt32(x));

// Some other place
converter.Convert<int>("12");


So far so good, but where it gets complicated is I want to write a non generic verison of convert like so



object Convert(object value, Type type)
{
var conversion = m_Conversions[type];
// ???
}


How do I do that? I thought of doing something like :



object Convert(object value, Type type)
{
var conversion = m_Conversions[type];
var funcType = typeof(Func<,>).MakeGenericType(typeof(object), type);
var invoke = funcType.GetMethod("Invoke");
return invoke.Invoke(conversion, new object[] { value });
}


But it seems very inefficient. Can you think of a better way of doing this?






Aucun commentaire:

Enregistrer un commentaire