How can I get an extension method to change the original object?

后端 未结 3 1118
-上瘾入骨i
-上瘾入骨i 2020-11-29 07:22

I want to be able to write extension methods so that I can say:

lines.ForceSpaceGroupsToBeTabs();

instead of:



        
3条回答
  •  萌比男神i
    2020-11-29 07:57

    You have to modify the contents of the List passed to the extension method, not the variable that holds the reference to the list:

    public static void ForceSpaceGroupsToBeTabs(this List lines)
    {
        string spaceGroup = new String('.', 4);
        for (int i = 0; i < lines.Count; i++)
        {
            lines[i] = lines[i].Replace(spaceGroup, "T");
        }
    }
    

提交回复
热议问题