设置c#匿名函数的参数值

本文关键字:参数 函数 设置 | 更新日期: 2023-09-27 18:11:04

假设我有以下代码

private Func<T> _method;
public void SetExecutableMethod<T>(Func<T> methodParam)
{
    _method = methodParam;
}
public T ExecuteMethod(object[] parameterValues)
{
    //get the number of parameters _method has;
    var methodCallExpression = _method.Body as MethodCallExpression;
    var method = methodCallExpression.Method;
    ParameterInfo[] methodParams = method.GetParameters();
    //So i now have a list of parameters for the method call,
    //How can i update the parameter values for each of these?
    for (int i = 0; i < parameters.Count(); i++ )
    {
        methodParams[i] = ???''
    }
    return _method.Compile()();
}
public void InitAndTest()
{
    SetExecutableMethod( () => _service.SomeMethod1("param1 placeholder", "param2 placeholder") );
    T result1 = ExecuteMethod(new object[]{"Test1", "Test2"});
    T result2 = ExecuteMethod(new object[]{"Test3", "Test4"}););
}

在上面的代码中,我想把私有变量设置为指向匿名函数的某个函数,并且永远不必再设置它。然后,我希望能够调用ExecuteMethod(…)与不同的参数。该方法应该更新变量_method的参数值,然后调用该方法。我可以读取参数的数量和它们的值很好,我只是不知道如何设置这些参数的值?对此有什么想法吗?

设置c#匿名函数的参数值

不应该这样做。现在,您的_method字段是Func<T>类型的委托,并且您期望它的包含实际执行的另一个方法。你对打电话的人期望太高了。我会忘记这种方法,寻找不同的方法。

一种方法是提供一个以对象数组作为参数的方法(Func<object[], T>),然后用适当的参数直接调用它(但绝不在其主体中使用方法)。即使这种情况在c#这样的强类型语言中也不太常见,因为你失去了所有的类型安全(但话说回来,你确实希望在你正在设计的框架中非常灵活)。

另一种方法是获取MethodInfo实例,然后使用它的Invoke方法。在某种程度上,这甚至可以更好地表达您的意图,因为很明显,可执行方法实际上可以做任何事情。

接下来,您可以使用泛型来获得某种类型安全,并要求将所有输入参数包装在单个参数类中。在这种情况下,您可能有一个强类型的Func<Tparam, Tresult>方法,而您的Execute方法将接受Tparam实例作为其参数。这样就不需要任何反射了。

[编辑]

当我写的时候,我会尽量避免反思。因为您写的基本上需要一个方法结果的缓存,一个简单的方法可能是这样的:

  1. 为您的参数列表创建一个包装器,以便您可以"按值"比较它们。我添加了一个示例类,但是您甚至可能希望允许显式地传递IEqualityComparer,这样您就不必为每个部分参数重写Equals

    // implements `IEquatable` for a list of parameters
    class Parameters : IEquatable<Parameters>
    {
        private readonly object[] _parameters;
        public Parameters(object[] parms)
        {
            _parameters = parms;
        }
        #region IEquatable<Parameters> Members
        public bool Equals(Parameters other)
        {
            if (other == null)
                return false;
            if (_parameters.Length != other._parameters.Length)
                return false;
            // check each parameter to see if it's equal
            // ...     
        }
        public override bool Equals(object obj)
        {
            return Equals(obj as Parameters);
        }
        public override int GetHashCode()
        { ... }
        #endregion
    }
    
  2. 为单个服务创建缓存。使用上面的包装器类,它应该简单地检查缓存结果是否存在:

    // contains cached results for a single service
    class CachedCallInfo
    {
        private readonly Func<object[], object> _method;
        private readonly Dictionary<Parameters, object> _cache
            = new Dictionary<Parameters, object>();
        public CachedCallInfo(Func<object[], object> method)
        {
            _method = method;
        }
        public T GetResult<T>(params object[] parameters)
        {
            // use out Parameters class to ensure comparison
            // by value
            var key = new Parameters(parameters);
            object result = null;
            // result exists?
            if (!_cache.TryGetValue(key, out result))
            {
                // do the actual service call
                result = _method(parameters);
                // add to cache
                _cache.Add(key, result);
            }
            return (T)result;
        }
    }
    
  3. 创建最后一个类,它将通过名称引用服务:

    public class ServiceCache
    {
        private readonly Dictionary<string, CachedCallInfo> _services =
            new Dictionary<string, CachedCallInfo>();
        public void RegisterService(string name, Func<object[], object> method)
        {
            _services[name] = new CachedCallInfo(method);
        }
        // "params" keyword is used to simplify method calls
        public T GetResult<T>(string serviceName, params object[] parameters)
        {
            return _services[serviceName].GetResult<T>(parameters);
        }
    }
    

你的缓存设置看起来像这样:

serviceCache.RegisterService("ServiceA", @params => DoSomething(@params));
serviceCache.RegisterService("ServiceB", @params => SomethingElse(@params));

你可以简单地这样称呼它:

var result = serviceCache.GetResult("ServiceA", paramA, paramB, paramC);

不知道为什么这是有用的,但这里是:

public class SomeCrazyClass<T>
{
    private Expression<Func<T>> _method;
    public void SetExecutableMethod(Expression<Func<T>> methodParam)
    {
        _method = methodParam;
    }
    public object ExecuteMethod(SomeService someService, object[] parameterValues)
    {
        var methodCallExpression = _method.Body as MethodCallExpression;
        var method = methodCallExpression.Method;
        var methodCall = Expression.Call(Expression.Constant(someService), method,
                                parameterValues.Select(Expression.Constant));
        return Expression.Lambda(methodCall).Compile().DynamicInvoke();
    }
}

这样写:

    public static void InitAndTest()
    {
        var something = new SomeCrazyClass<int>(); //or whatever type your method returns
        var _service = new SomeService();
        something.SetExecutableMethod(() => _service.SomeMethod1("param1 placeholder", "param2 placeholder"));
        var result1 = something.ExecuteMethod(_service,new object[] {"Test1", "Test2"});
        var result2 = something.ExecuteMethod(_service, new object[] {"Test3", "Test4"});
    }

我个人认为你太过分了,除非有一个覆盖架构需要将lambda作为表达式树来处理。但是,我离题了。

与其使用反射元素(它们基本上只是根据表达式树进行描述),不如查看MethodCallExpression的Arguments成员。它将包含几个ContantExpression对象,您可以用自己的ConstantExpressions替换它们,其中包含您想要传入的字符串值。然而,表达式是只读的;你必须为这个调用重新构建一个等价的树。

public class FuncManipulator<T>
{
    private Func<T> _method;
    public void SetExecutableMethod(Func<T> methodParam)
    {
        _method = methodParam;
    }
    //you forgot the "params" keyword
    public T ExecuteMethod(params object[] parameterValues)
    {
        //get the number of parameters _method has;
        var methodCallExpression = _method.Body as MethodCallExpression;
        var arguments = methodCallExpression.Arguments;
        var newArguments = new List<Expression>();        
        for (int i = 0; i < arguments.Count(); i++ )
        {
            newArguments.Add(Expression.Constant(parameterValues[i]));
        }
        //"Clone" the expression, specifying the new parameters instead of the old.
        var newMethodExpression = Expression.Call(methodCallExpression.Object, 
                                                  methodCallExpression.Method, 
                                                  newArguments)
        return newMethodExpression.Compile()();
    }
}
...
public void InitAndTest()
{
    SetExecutableMethod( () => _service.SomeMethod1("param1 placeholder", "param2 placeholder") );
    T result1 = ExecuteMethod("Test1", "Test2");
    T result2 = ExecuteMethod("Test3", "Test4");
    T result3 = ExecuteMethod("Test6", "Test5");
}

只要表达式树能找到MethodCallExpression引用的函数,这就可以工作。

然而,我认为有一个更简单的方法:

public class FuncManipulator<T>
{
    private Func<T> _method;
    public void SetExecutableMethod(Func<T> methodParam)
    {
        _method = methodParam;
    }
    //you must pass the actual array; we are creating a closure reference that will live
    //as long as the delegate
    public void SetMethodParams(object[] param)
    {
        _param = param;
    } 
    public T ExecuteMethod(params object[] passedParam)
    {
       //We have to re-initialize _param based on passedParam
       //instead of simply reassigning the reference, because the lambda
       //requires we don't change the reference.
       for(int i=0; i<_param.Length; i++)
          _param[i] = passedParam.Length <= i ? null : passedParam[i];
       //notice we don't pass _param; the lambda already knows about it
       //via the reference set up when declaring the lambda.
       return _method(); 
    }
}
...
public void InitAndTest()
{
    //this is an "external closure" we must keep in memory
    object[] param = new object[2];
    SetExecutableMethod( () => _service.SomeMethod1(param[0], param[1]) );
    //We do so by passing the reference to our object
    SetMethodParams(param);
    //now, don't ever reassign the entire array.
    //the ExecuteMethod function will replace indices without redefining the array.
    T result1 = ExecuteMethod("Test1", "Test2");
    T result2 = ExecuteMethod("Test3", "Test4");
    T result3 = ExecuteMethod("Test6", "Test5");
}