将类成员作为函数参数传递

时间:2019-11-04 11:35:10

标签: c#

我想在一个函数内做一个嵌套循环,但是第二个循环的成员由function参数决定,如何使其工作?像这样:

List<Book> listBook;
List<Employee> listEmployee;

class Book
{
    string title;
    List <string> chapters;
}

class Employee
{
    string name;
    List <string> skills;
    List <string> jobs;
}


void Loop(List<object> list, Member mem)
{
    foreach (var i in list)
    {
        foreach (var j in i.mem)
        {
            string str = (string)j;
            ..................

        }
    }
}

void Main()
{
    Loop(listBook, Book.chapters);
    Loop(listEmployee, Employee.jobs);
}

1 个答案:

答案 0 :(得分:3)

您可以对委托使用通用方法:

void Loop<T>(IEnumerable<T> list, Func<T, List<string>> member)
{
    foreach (var i in list)
    {
        foreach (var j in member(i))
        {
            // ...    
        }
    }
}

并像这样使用它:

void Main()
{
    Loop(listBook, x => x.chapters);
    Loop(listEmployee,  x => x.jobs);
}