扩展方法和本地'this'变量

Art*_*Rey 7 c# extension-methods local ref

据我所知this,扩展方法作为ref变量传递.我可以通过这样做验证这一点

public static void Method<T>(this List<T> list)
{
    list.Add(default(T));
}

List<int> ints = new List<int>(new int[] { 1, 2, 3, 4, 5 });
ints.Method();
Run Code Online (Sandbox Code Playgroud)

List<int> ints现在1, 2, 3, 4, 5, 0.

但是,当我这样做

public static void Method<T>(this List<T> list, Func<T, bool> predicate)
{
    list = list.Where(predicate).ToList();
}

List<int> ints = new List<int>(new int[] { 1, 2, 3, 4, 5 });
ints.Method(i => i > 2);
Run Code Online (Sandbox Code Playgroud)

我希望我List<int> ints3, 4, 5保持原状但仍然保持原状.我错过了一些明显的东西吗

Kap*_*pol 5

this扩展方法参数由值来传递,而不是通过引用.这意味着在进入扩展方法时,您有两个指向相同内存地址的变量:原始intslist参数.当您将项目添加到扩展方法内的列表时,它会反映在中ints,因为您修改了两个变量引用的对象.重新分配时list,将在托管堆上创建新列表,并且扩展方法的参数指向此列表.该ints变量仍指向旧列表.