例如,我很少需要:
using System.Text;
但它总是默认存在的。如果代码中包含不必要的using指令,我假设应用程序将使用更多内存。但是还有什么我应该注意的吗?
同样,如果同一个using指令只在一个文件中使用,而在大多数/所有文件中使用,会有任何区别吗?
编辑:请注意,这个问题不是关于不相关的概念,称为using语句,旨在帮助管理资源,确保当一个对象超出作用域时,它的IDisposable。方法被调用。参见c#中“using”的用法。
例如,我很少需要:
using System.Text;
但它总是默认存在的。如果代码中包含不必要的using指令,我假设应用程序将使用更多内存。但是还有什么我应该注意的吗?
同样,如果同一个using指令只在一个文件中使用,而在大多数/所有文件中使用,会有任何区别吗?
编辑:请注意,这个问题不是关于不相关的概念,称为using语句,旨在帮助管理资源,确保当一个对象超出作用域时,它的IDisposable。方法被调用。参见c#中“using”的用法。
当前回答
除了编码偏好之外,删除未使用的using(s)/命名空间还有几个原因:
removing the unused using clauses in a project, can make the compilation faster because the compiler has fewer namespaces to look-up types to resolve. (this is especially true for C# 3.0 because of extension methods, where the compiler must search all namespaces for extension methods for possible better matches, generic type inference and lambda expressions involving generic types) can potentially help to avoid name collision in future builds when new types are added to the unused namespaces that have the same name as some types in the used namespaces. will reduce the number of items in the editor auto completion list when coding, posibly leading to faster typing (in C# 3.0 this can also reduce the list of extension methods shown)
删除未使用的名称空间不会做什么:
以任何方式改变编译器的输出。 以任何方式改变已编译程序的执行(更快的加载或更好的性能)。
无论是否删除未使用的using,生成的程序集都是相同的。
其他回答
不要忘记编译器在构建项目时做了很多工作来优化所有内容。使用that在很多地方都被使用,或者1在编译后不应该做不同的事情。
当程序运行时,它不会改变任何东西。所需的一切都是按需装载的。所以即使你有using语句,除非你在命名空间/程序集中实际使用了一个类型,否则与using语句相关的程序集不会被加载。
主要是为了个人喜好。
它们只是作为一种捷径。例如,你必须这样写: 系统。Int32每次如果你没有一个使用系统;在上面。
删除未使用的元素只会使代码看起来更干净。
using语句不会影响性能,因为它只是限定标识符名称的一个助手。因此,如果你使用System.IO,你不必输入System.IO.Path.Combine(…),你可以简单地输入Path.Combine(…)。
如果你想保持你的代码干净,不使用的using语句应该从文件中删除。当你在一个需要理解你的代码的协作团队中工作,认为你所有的代码都必须维护,更少的代码=更少的工作,好处是长期的。