如何获得扩展方法来更改原始对象? [英] How can I get an extension method to change the original object?
本文介绍了如何获得扩展方法来更改原始对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够编写扩展方法,以便我可以说:
I want to be able to write extension methods so that I can say:
lines.ForceSpaceGroupsToBeTabs();
代替:
lines = lines.ForceSpaceGroupsToBeTabs();
但是,以下代码当前输出:
However, the following code currently outputs:
....one
........two
代替:
Tone
TTtwo
我必须在以下代码中更改什么才能使其输出:
Tone
TTtwo
(注意,对于可见性,.= space, T =
):
(note that for visibility, . = space, T =
):
using System;
using System.Collections.Generic;
namespace TestExtended82343
{
class Program
{
static void Main(string[] args)
{
List<string> lines = new List<string>();
lines.Add("....one");
lines.Add("........two");
lines.ForceSpaceGroupsToBeTabs();
lines.ForEach(l => Console.WriteLine(l));
Console.ReadLine();
}
}
public static class Helpers
{
public static void ForceSpaceGroupsToBeTabs(this List<string> originalLines)
{
string spaceGroup = new String('.', 4);
List<string> lines = new List<string>();
foreach (var originalLine in originalLines)
{
lines.Add(originalLine.Replace(spaceGroup, "T"));
}
originalLines = lines;
}
}
}
推荐答案
你必须修改传递给扩展方法的 List
的内容,而不是保存引用的变量名单:
You have to modify the contents of the List<string>
passed to the extension method, not the variable that holds the reference to the list:
public static void ForceSpaceGroupsToBeTabs(this List<string> lines)
{
string spaceGroup = new String('.', 4);
for (int i = 0; i < lines.Count; i++)
{
lines[i] = lines[i].Replace(spaceGroup, "T");
}
}
这篇关于如何获得扩展方法来更改原始对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文