我有一个Employee类,其中包含一些基本参数,还有一个class雇员,其中有一个employee对象列表。我想在班级员工中使用func委托,以便能够在主类中使用以下lambda表达式。我想我在这里有一些语法错误...我收到以下错误消息:“无法将lambda表达式转换为类型'Employee',因为它不是委托类型”。

有人知道我做错了吗?

非常感谢你们!

static void Main(string[] args)
        {
            Employees lijst = new Employees();
            lijst.Add(new Employee("B1", 200));
            lijst.Add(new Employee("B2", 100));
            lijst.Add(new Employee("B3", 300));

            lijst.Wijzig((Employee b) => b.Salary += 100);

            Console.ReadKey();
        }


class Employee
    {
        public String Name { get; set; }
        public int Salary { get; set; }



        public Employee(String Name, int Salary)
        {
            this.Name = Name;
            this.Salary = Salary;

        }
    }


class Employees
    {
        public Func<Employee, int> Wijzig = new Func<Employee, int>(Change);
        private ArrayList _lijst = new ArrayList();

        public void Add(Employee e)
        {
            _lijst.Add(e);
        }

        static int Change(Employee b)
        {

            return 0;
        }
    }

最佳答案

这是我的解决方案,在Main函数中没有任何变化:

    static void Main(string[] args)
    {
        Employees lijst = new Employees();
        lijst.Add(new Employee("B1", 200));
        lijst.Add(new Employee("B2", 100));
        lijst.Add(new Employee("B3", 300));

        lijst.Wijzig((Employee b) => b.Salary += 100);

        lijst.Print();

        Console.ReadKey();
    }


    class Employee
    {
        public String Name { get; set; }
        public int Salary { get; set; }

        public Employee(String Name, int Salary)
        {
            this.Name = Name;
            this.Salary = Salary;
        }
    }


    class Employees
    {
        // [Delete]
        // public Func<Employee, int> Wijzig = new Func<Employee, int>(Change);
        private ArrayList _lijst = new ArrayList();

        public void Add(Employee e)
        {
            _lijst.Add(e);
        }

        // [Delete]
        //static int Change(Employee b)
        //{
        //    return 0;
        //}

        // [New]
        public void Wijzig(Func<Employee, int> func)
        {
            foreach (Employee e in _lijst)
            {
                func(e);
            }
        }

        public void Print()
        {
            foreach (Employee e in _lijst)
            {
                Console.WriteLine(e.Name + "\t" + e.Salary);
            }
        }
    }

关于c# - C#Func委托(delegate)与Lambda表达式组合使用不正确,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44588070/

10-11 01:44