[英]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
)参考不变。
当您将结果重新分配为result
, result
现在将引用新对象,并且指向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.