策略设计模式问题代表C#

时间:2018-12-06 01:14:09

标签: c# delegates strategy-pattern

我很难使用委托和策略模式。有两个奖学金。我想挑选一个符合奖学金条件的学生。没用对于if(pickup)行,它显示错误“无法将类型'StudentGroup.Pickup'隐式转换为'bool'。怎么解决呢?谢谢。还有其他错误吗?谢谢。

public class Student
{
    public string name;
    public int year; //1 to 4
    public double gpa; //0-4.0
}

public class StudentGroup
{
    private List<Student> students = new List<Student>();
    private Random rnd = new Random();
    public delegate bool Pickup(Student x);
    public void AddStudent(string name, int year, double gpa)
    {
        Student s = new Student();
        s.name = name;
        s.year = year;
        s.gpa = gpa;
        students.Add(s);
    }

    public Student PickFor(Pickup pickup)
    {
        List<Student> candidates = new List<Student>();
        foreach (Student s in students)
        {
            if (pickup)
                candidates.Add(s);
        }

        if (candidates.Count > 0)
            return candidates[rnd.Next(candidates.Count)];
        else
            return null;
    }
}

public class Program
{
    public static void Main()
    {
        StudentGroup sg = new StudentGroup();
        sg.AddStudent("Peter", 2, 3.2);
        Student candidate1 = sg.PickFor(s => s.gpa >= 3.8);
        Student candidate2 = sg.PickFor(s => s.gpa >= 3.0 && s.year == 1);
    }
}

1 个答案:

答案 0 :(得分:2)

您的代答委托需要一个类型为Student的参数,因此请确保在if语句中传递该参数,并确保您正在对委托进行某些操作。

if (pickup(s))
    candidates.Add(s);