mercredi 18 mars 2015

Utilizing a Func to improve reflection performance for generic types

I've been doing some investigatory work improving the performance of methods invoked using reflection based on the article and comments on Jon Skeet's blog here.


http://ift.tt/1Aa0ap9


Based on one of the comments (formatting is broken in the blog comments) I have the following method.



private static Func<T, object, object> MagicMethod<T>(MethodInfo method)
{
var parameter = method.GetParameters().Single();
var instance = Expression.Parameter(typeof(T), "instance");
var argument = Expression.Parameter(typeof(object), "argument");

var methodCall = Expression.Call(
instance,
method,
Expression.Convert(argument, parameter.ParameterType));

return Expression.Lambda<Func<T, object, object>>(
Expression.Convert(methodCall, typeof(object)),
instance,
argument).Compile();
}


Which I can use to return dynamically invoked methods like the one in the example code.



private static readonly MethodInfo IndexOfMethod =
typeof(string).GetMethod("IndexOf", new[] { typeof(char) });

public static object IndexOf(string s, char c)
{
var i = MagicMethod<string>(IndexOfMethod);
return i(s,c);
}


This should be good and quick.


I'm trying to apply the approach now to generic methods like Enumerable.Cast<T> but can't seem to get anywhere.


I have my MethodInfo.



private static readonly MethodInfo CastMethod =
typeof(Enumerable).GetMethod("Cast");


But I am now lost in the syntax. I can't use the static Enumerable type as a generic type argument so I don't know what to do.


Could someone give me an example?






Aucun commentaire:

Enregistrer un commentaire