考虑以下语句:
recorder.AddActivity(new Activity { ActivityName = "DeepSeaDiving", DayOfWeek = DayOfWeek.Monday });
取而代之的是,这里有一个帖子,用于Expression Trees
像这样进行花哨的调用:
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;
}
但是,当我编译它时,编译器对扩展方法不满意,并抱怨 `Cannot convert sourceType ParameterExpression to DayOfWeek。
上面使用的类的相关代码如下:
public class Activity
{
/// <summary>
/// Gets the activity name.
/// </summary>
public string ActivityName { get; set; }
/// <summary>
/// Gets The day of week.
/// </summary>
public DayOfWeek DayOfWeek { get; set; }
}
public class WeeklyActivityRecorder
{
private List<Activity> Activities { get; set; }
public WeeklyActivityRecorder()
{
}
public List<Activity> GetAllActivities()
{
return this.Activities;
}
public void AddActivity(Activity activity)
{
if (this.Activities == null)
{
this.Activities = new List<Activity>();
}
if (activity != null)
{
this.Activities.Add(activity);
}
}
}
有什么想法我在这里想念的吗?