简体   繁体   English

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

[英]strategy design pattern problem delegates c#

I have trouble to use delegates and the Strategy pattern. 我很难使用委托和策略模式。 There are two scholarships. 有两个奖学金。 I want to pick a random student that fulfill the scholarship criteria. 我想挑选一个符合奖学金条件的学生。 It doesn't work. 没用 For the line if (pickup), it shows error "Cannot implicitly convert type 'StudentGroup.Pickup' to 'bool". 对于if(pickup)行,它显示错误“无法将类型'StudentGroup.Pickup'隐式转换为'bool'。 How to solve it? 怎么解决呢? Thank you. 谢谢。 Is there any other error? 还有其他错误吗? Thanks. 谢谢。

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

Your Pickup delegate requires an argument of type Student, so make sure to pass it one in your if statement, and also make sure you are doing something with your delegate. 您的代答委托需要一个类型为Student的参数,因此请确保在if语句中传递该参数,并确保您正在对委托进行操作。

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

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

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