C# 如何将某些using语句设置为不冗余,即使它们是冗余的?

C# 如何将某些using语句设置为不冗余,即使它们是冗余的?,c#,visual-studio-2015,resharper,settings,using-statement,C#,Visual Studio 2015,Resharper,Settings,Using Statement,创建文件时,通常以一组常见的using语句开始。有时,即使在充实了类之后,我也不需要使用一些自动生成的语句。但是,如果最终需要它们,删除它们可能会导致问题,例如使用System.Linq删除它们所导致的问题; 有没有办法告诉Visual Studio/Resharper不要抱怨某些using语句是多余的 例如: using System; using System.Collections.Generic; // Don't need but want anyway without an erro

创建文件时,通常以一组常见的using语句开始。有时,即使在充实了类之后,我也不需要使用一些自动生成的语句。但是,如果最终需要它们,删除它们可能会导致问题,例如使用System.Linq删除它们所导致的问题; 有没有办法告诉Visual Studio/Resharper不要抱怨某些using语句是多余的

例如:

using System;
using System.Collections.Generic; // Don't need but want anyway without an error
using System.Linq; // Don't need but want anyway without an error
using System.Net;
using System.Text; // Don't need but want anyway without an error
using Acceptance.EndToEnd.Helpers;
using Acceptance.EndToEnd.Locators;

你也可以把它们移走,但正如已经指出的,把它们留在里面并没有坏处

如果您确实删除了它们,VisualStudio/ReSharper将根据需要将它们重新添加到中—如果您使用ReSharper,甚至还会添加到System.Linq中

如果您确实需要,您可以在单击灯泡时关闭此警告以停止ReSharper抱怨:


您可以使用ChrisF的答案,也可以添加ReSharper注释来禁用代码中的警告

使用

在文件开头禁用整个文件中的警告或使用

// ReSharper disable once RedundantUsingDirective
using Namespace.That.I.Dont.Need
要使用语句禁用单个
的警告,请使用

// ReSharper disable RedundantUsingDirective
using Namespace.That.I.Dont.Need
using Another.Namespace.That.I.Dont.Need
// ReSharper restore RedundantUsingDirective
using Namespace.That.I.Do.Need

用于多个名称空间。

ReSharper提供了一种更好的方法:


如果你离开他们,我不明白问题出在哪里。你没有任何错误,是吗?我不使用ReSharper,但从VS2015开始,它只是告诉您不需要的用法。但如果忽略VS2015,就不会遇到任何问题。它仍然会编译,如果不使用它们,就不会加载它们,因此没有性能成本,那么你为什么要在意呢?我理解OP,因为我喜欢清理代码并删除未使用的语句。特别是在我的测试项目中(我在其中试验了不同的代码片段):在.NET framework的不同名称空间中有同名的类(例如Windows.Forms vs.WPF)。如果我在我的文件中留下所有我需要的
语句,我有时会使用错误的类,并且意识到太晚了。这确实发生了。
// ReSharper disable RedundantUsingDirective
using Namespace.That.I.Dont.Need
using Another.Namespace.That.I.Dont.Need
// ReSharper restore RedundantUsingDirective
using Namespace.That.I.Do.Need