扩展方法和局部"this"变量 [英] Extension method and local 'this' variable

查看:44
本文介绍了扩展方法和局部"this"变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,扩展方法中的 this 作为 ref 变量传递.我可以这样做来验证

To my knowledge this in a extension method is passed as a ref variable. I can verify this by doing

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();

我的 List< int>整数现在为 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);

我希望我的 List< int>ints 3、4、5 ,但保持不变.我缺少明显的东西吗?

I would expect my List<int> ints to be 3, 4, 5 but remains untouched. Am I missing something obvious?

推荐答案

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

The this extension method parameter is passed by value, not by reference. What this means is that upon entering the extension method, you have two variables pointing to the same memory address: the original ints and the list parameter. When you add an item to the list inside the extension method, it is reflected in ints, because you modify an object referenced by both variables. When you reassign list, a new list is created on the managed heap and the extension method's parameter points to this list. The ints variable still points to the old list.

这篇关于扩展方法和局部"this"变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆