C# .NET 4.0 中反射的最佳替代品
本文关键字:反射的 最佳 替代品 NET | 更新日期: 2023-09-27 18:31:09
我面临着以下通过反射检索数据的代码:
public object GetValue(object source)
{
if (Member == null) return Argument;
try
{
object[] argList = (Argument == null ? null : new object[] { Argument });
if (Member is PropertyInfo) return ((PropertyInfo)Member).GetValue(source, argList);
if (Member is MethodInfo) return ((MethodInfo)Member).Invoke(source, argList);
if (Member is FieldInfo) return ((FieldInfo)Member).GetValue(source);
throw new Exception("Unknown member type: " + Member);
}
catch (Exception ex)
{
throw new Exception("Could not get value " + Member.Name + " from " + source + " with " + Argument, ex);
}
}
然而,这非常慢,我正在考虑用更快的东西替换反射,也许是代表们?但是,我不确定代表是最佳选择,或者在这种情况下如何实现它。我正在运行.NET 4.0。任何建议不胜感激!
这有点快
static Func<object, object[], object> BuildCaller(MethodInfo method)
{
var obj = Expression.Parameter(typeof(object));
var pars = Expression.Parameter(typeof(object[]));
var pars2 = method.GetParameters();
var casted = new Expression[pars2.Length];
for (int i = 0; i < pars2.Length; i++)
{
casted[i] = Expression.Convert(Expression.ArrayAccess(pars, Expression.Constant(i)), pars2[i].ParameterType);
}
var call = Expression.Call(Expression.Convert(obj, method.DeclaringType), method, casted);
var cast = Expression.Convert(call, typeof(object));
var lamdba = Expression.Lambda<Func<object, object[], object>>(cast, obj, pars);
return lamdba.Compile();
}
static Func<object, object[], object> BuildCaller(FieldInfo field)
{
var obj = Expression.Parameter(typeof(object));
var pars = Expression.Parameter(typeof(object[]));
var call = Expression.Field(Expression.Convert(obj, field.DeclaringType), field);
var cast = Expression.Convert(call, typeof(object));
var lamdba = Expression.Lambda<Func<object, object[], object>>(cast, obj, pars);
return lamdba.Compile();
}
static Func<object, object[], object> BuildCaller(PropertyInfo property)
{
var obj = Expression.Parameter(typeof(object));
var pars = Expression.Parameter(typeof(object[]));
var pars2 = property.GetIndexParameters();
var casted = new Expression[pars2.Length];
for (int i = 0; i < pars2.Length; i++)
{
casted[i] = Expression.Convert(Expression.ArrayAccess(pars, Expression.Constant(i)), pars2[i].ParameterType);
}
var call = Expression.Property(Expression.Convert(obj, property.DeclaringType), property, casted);
var cast = Expression.Convert(call, typeof(object));
var lamdba = Expression.Lambda<Func<object, object[], object>>(cast, obj, pars);
return lamdba.Compile();
}
我创建了一个预缓存该方法的委托(通过 Expression
s)。如果Arguments
是"固定的",你可以更进一步,甚至预缓存它们的转换(就像每次调用该方法时都会完成转换一样)
这是方法的一个示例。对于属性和字段,它是相似的(对于字段,它甚至更容易)。
和一个例子
var fun = BuildCaller(typeof(MyClass).GetMethod("MyMethod"));
var mc = new MyClass();
fun(mc, new object[] { 1, 2.0 });
您必须将fun
与Method
一起缓存