调用在 C# 中在其参数中使用表达式和委托的扩展方法

本文关键字:扩展 方法 参数 调用 表达式 | 更新日期: 2023-09-27 18:36:07

请考虑以下语句:

recorder.AddActivity(new Activity { ActivityName = "DeepSeaDiving", DayOfWeek = DayOfWeek.Monday });

取而代之的是,这里有一个帖子,用Expression Trees像这样花哨地打电话:

WeeklyActivityRecorder weeklyActivities = new WeeklyActivityRecorder () .WithActivities( Monday => "Lawn Moving",Tuesday => "Cooking");

我在这里看到了扩展方法,如下所示。

public static WeeklyActivityRecorder WithActivities(this WeeklyActivityRecorder recorder, params Expression<Func<DayOfWeek, string>>[] activityList) 
    {
    foreach (var activity in activityList)
                {
                    LambdaExpression expression = activity;
                    ConstantExpression enteredActivity = expression.Body as ConstantExpression;
                    DayOfWeek day = expression.Parameters[0];
                    recorder.AddActivity(new Activity{DayOfWeek = day, ActivityName = activity});
                }
                return recorder;
    }

但是,当我编译它时,编译器对扩展方法不满意,并抱怨"无法将sourceType ParameterExpression转换为DayOfWeek

知道我在这里错过了什么吗?

调用在 C# 中在其参数中使用表达式和委托的扩展方法

你需要传递一个有效的lambda..你传递一个实际的DayOfWeek

recorder.WithActivities(lambda_variable_here => "LawnMoving");

您需要传递参数,但您尝试创建 lambda,其中参数名称是静态属性,大致相当于:

public string SomeMethodName(DayOfWeek.Monday) //incorrect method declaration
{
}

您需要调用WithActivities方法,例如

recorder.WithActivities(dayOfWeek => "LawnMoving"); //dayOfWeek is a parameter name

如果需要将转换方法从 DayOfWeek 传递到 String ,可以使用字典,如下所示:

var recorder = new WeeklyActivityRecorder();
var daysTranslation = new Dictionary<DayOfWeek, string>()
{
    {DayOfWeek.Monday, "LawnMoving"}
    //other pairs
};
recorder.WithActivities(dayOfWeek => daysTranslation[dayOfWeek]);