简体   繁体   English

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

[英]Calling an extension method that uses expressions and delegates in its parameter in C#

Consider the below statement: 请考虑以下声明:

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

Instead of this, there was a post here , using Expression Trees for fancy-calling like this: 取而代之的是,有一个帖子在这里 ,使用Expression Trees的呼看中这样的:

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

I saw that extension method here , and which is given below. 我在这里看到了这个扩展方法,下面给出了这个方法。

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;
    }

But, when I compile this, the compiler is unhappy about the extension method and complains that `Cannot convert sourceType ParameterExpression to DayOfWeek . 但是,当我编译它时,编译器对扩展方法不满意并且抱怨“无法将sourceType ParameterExpression转换为DayOfWeek”

Any ideas what I am missing here ? 我在这里缺少什么想法?

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

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

You need to pass parameter, but you try to create lambda, where parameter name is static property, which is roughly equivalent to: 您需要传递参数,但是您尝试创建lambda,其中参数名称是静态属性,大致相当于:

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

}

You need to call WithActivities method like 你需要调用WithActivities方法

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

If you need to pass conversion method from DayOfWeek to String , you can use Dictionary, like this: 如果需要将转换方法从DayOfWeek传递给String ,可以使用Dictionary,如下所示:

var recorder = new WeeklyActivityRecorder();

var daysTranslation = new Dictionary<DayOfWeek, string>()
{
    {DayOfWeek.Monday, "LawnMoving"}
    //other pairs
};

recorder.WithActivities(dayOfWeek => daysTranslation[dayOfWeek]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM