簡體   English   中英

將擴展方法添加到列表

[英]Add extension method to List

這是我的代碼

class Student
{
    some code 
}

static class Filter
{
    static void TypeFilter(this List<Student> result, string type)
    {
        result = result.FindAll(x=>x.type == type);
    }
}

當我使用這種擴展方法時

    List<Student> a = some code;
    a.TypeFilter("someType");

列表a沒有被過濾,列表應該是引用類型,那么為什么a沒有變化,我做錯了什么嗎?

這就是為什么您看不到結果:

static void TypeFilter(this List<Student> result, string type)
{
    result = result.FindAll(x=>x.type == type);
}

List<Student> a = some code;
a.TypeFilter("someType");

按defualt傳遞的參數按值傳遞。 result現在是引用列表的局部變量。 當你打電話FindAll -你得到一個新的參考-原來的列表result (與a )參考不變。

當您將結果重新分配為resultresult現在將引用新對象,並且指向a的鏈接已斷開。 a所有這些方面, a都保持不變。

大多數Linq方法返回一個新對象,而不是修改傳入的對象。 如果您遵循該模式,則您的方法將是

static List<Student> TypeFilter(this List<Student> result, string type)
{
    return result.FindAll(x=>x.type == type);
}

用法是:

List<Student> a = some code;
a = a.TypeFilter("someType");

您可以使用RemoveAll

static void TypeFilter(this List<Student> result, string type)
{
    result.RemoveAll(x=>x.type != type);
}

您不能通過這種方式分配它,請嘗試以下操作:

static List<Student> TypeFilter(this List<Student> result, string type)
    {
       return result.FindAll(x=>x.type == type);
    }

像這樣使用它:

List<Student> a = some code;
List<Student> filteredStudentList = a.TypeFilter("someType");

A是引用類型,但是在調用FindAll時創建了一個新的List。 FindAll是一個返回新列表的函數。 它等效於foolow方法:

List<Student> FindAll (List<Student> students, string filter){
    List<Student> newList = new List<Student>();

    foreach(var student in students){
        if(filter == student.type)
            newList.Add(student);
    }
    return newList;
}

如果要使用返回值,則需要通過創建變量來捕獲對返回值的引用:

varfilteredStudents = students.TypeFilter(“ someFilter”);

你不能分配給this指針的參考方法,並進行參數的任何方法不能分配給它,而不使其成為一個ref參數,因此List你代碼生成不能被分配到result你所描述的方式。

由於它是一個List ,因此您可以遍歷並刪除項目,而不必替換指針。

static void TypeFilter(this List<Student> result, string type)
{
    foreach(var s in result
        .Except(result.FindAll(x => x.type == type))
        .ToArray())  // VERY Important - modifying a list while iterating through it will throw an exception!
    { result.remove(s); }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM