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

我想在一个函数内做一个嵌套循环,但是第二个循环的成员由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);
}
yin088 回答:将类成员作为函数参数传递

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

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);
}
本文链接:https://www.f2er.com/3167104.html

大家都在问