移除未使用的 Using

    从MSDN看到一篇关于using管理的一篇文章,感觉不错,原文:http://msdn.microsoft.com/zh-cn/library/bb514115.aspx

Visual Studio 用户界面中的“移除未使用的 Using”选项用于移除源代码中未使用的 using 指令、using 别名和 extern 别名。调用该操作有两种方式:

  • 主菜单:在“编辑”菜单上指向“IntelliSense”,再指向“组织 Using”,然后单击“移除未使用的 Using”

  • 上下文菜单:右击代码编辑器中的任意位置,指向“组织Using”,再单击“移除未使用的 Using”

    说明:

    如果对未生成的源代码执行“移除未使用的 Using”,则可能会移除某些必需的 using 指令。

下面的示例显示了对源代码执行“移除未使用的 Using”所生成的结果。

执行之前

执行之后

using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("test");
        }
    }
}
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("test");
        }
    }
}

在前面的示例中,只有 System 将在以后用于源代码中。其他 using 指令(包括重复的 System using 指令)将被移除。

条件预处理器指令

“移除未使用的 Using”仅移除活动块中未使用的指令和别名。下面的示例阐释了这一点:

执行之前

执行之后

#define DEBUG

#if DEBUG

using System;

using System.Collections.Generic;

using System.Linq;

#else

using System.Text;

#endif

namespace ConsoleApplication1

{

class Program

{

static void Main(string[] args)

{

List<int> myList = new List<int> { 1, 2, 3 };

Console.WriteLine(myList);

}

}

}

#define DEBUG

#if DEBUG

using System;

using System.Collections.Generic;

#else

using System.Text;

#endif

namespace ConsoleApplication1

{

class Program

{

static void Main(string[] args)

{

List<int> myList = new List<int> { 1, 2, 3 };

Console.WriteLine(myList);

}

}

}

在上例中,既未使用 System.Text,也未使用 System.Linq。但是,由于 System.Text 不在活动块中,因此只会移除System.Linq

注释

只有注释位于指令或别名的标记之间时,“移除未使用的 Using”才会移除注释。出现在标记之前或之后的注释都不受影响。下面的示例阐释了这一点:

执行之前

执行之后

using System;

/* Comment before remains */

using /* Comment between removed */ System.Linq;

// Comment after remains

namespace ConsoleApplication1

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("My Example");

}

}

}

using System;

/* Comment before remains */

// Comment after remains

namespace ConsoleApplication1

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("My Example");

}

}

}

在上面的示例中移除了 System.Linq。只会移除位于指令标记之间的注释。

原文地址:https://www.cnblogs.com/myssh/p/1512586.html