0

我面临以下通过反射检索数据的代码:

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。任何建议表示赞赏!

4

1 回答 1

1

这有点快

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

于 2013-09-13T15:09:24.963 回答