有没有办法告诉编译器在某处放置一段代码?

时间:2011-10-03 14:42:12

标签: c# visual-studio

我有一个很长的方法,为了阅读清晰,我想将一些代码放在一个单独的方法中。但是,由于该代码使用方法中的变量,因此无法完成。所以我想将该代码放在其他地方并告诉编译器在编译时将该代码插入“this”位置。有没有办法做到这一点? 我正在使用visual studio。

5 个答案:

答案 0 :(得分:5)

听起来您正在描述Extract method,您可以非常轻松地执行此操作,只需突出显示您要移动的代码即可:

右键单击 - >重构 - >提取方法 - >输入方法名称

Visual Studio将为您处理其余部分。阅读文档here

答案 1 :(得分:5)

正如其他人所说,首先出现问题的事实是代码组织问题较大的症状。理想情况下,您的方法应该很短,并且变量很少,因此您无需将代码的大部分内容移动到其他位置。正确的做法可能是将部分代码提取到自己的方法中,每个方法执行一项任务并做得很好。

作为权宜之计,您可以使用代码区域来帮助整理代码:

void BigMethod()
{
    #region Frobbing code
        FrobTheBlob();
        // blah blah blah
        // blah blah blah
    #endregion
    ...

现在在Visual Studio中,编辑器会让你将该区域折叠成一行“Frobbing code”。

答案 2 :(得分:4)

如果您有一个长方法,因为您需要访问相同的本地人而无法拆分,那么真正所拥有的是另一个您尚未正式成为类的对象。重构代码,将方法和共享状态提取到自己的类中,然后开始将方法重构为更小,更易于管理的部分。

class SomeClass
{
    // whatever shared state of the class     
    // whatever methods of the class

    public void MethodThatsDoingTooMuch()
    {
         // long method
         // hard to split the method because of locals
    }
}

class SomeClass
{
    // whatever shared state of the class     
    // whatever methods of the class     

    public void MethodThatIsntDoingTooMuch()
    {
        bigSomethingDoer.Do();
    }
}

class BigSomethingDoer
{
    // shared locals are fields instead

    public void Do() 
    {
        // refactor long method into smaller methods
        // shared locals are promoted to class fields
        // this smaller class only does this one thing
        // --> its state does not pollute another class
    }
}

答案 3 :(得分:1)

你问的问题可能是用宏来完成的,但是如果代码很多而且不可读,你应该考虑重构它并创建另一个接受main方法中的变量作为参数的方法。

一些重构工具有 extract-method 等功能,您可以在其中选择一些代码,然后将其移至另一种方法。我想ReSharper和DevExpress CodeRush都有这个功能,但我不是100%肯定,我现在没有安装它们来试试这个。

答案 4 :(得分:0)

您可以使用匿名方法/ lambdas来创建可以访问包含方法的局部变量的函数。

但通常没有必要使用这么长的方法。尝试解耦方法的不同部分,以便它们不需要共享公共局部变量。