简体   繁体   English

c#将命名空间声明添加到所有类

[英]c# add using declaration for namespace to all classes

Is it possible to add a using declaration to a namespace globally? 是否可以在全局命名空间中添加using声明?

For example, I want all of my classes under the "MyApp.Models" namespace to include the namespace System.Linq.Dynamic. 例如,我希望“MyApp.Models”命名空间下的所有类都包含命名空间System.Linq.Dynamic。

In asp.net you can do this for view by adding the namespace in the web.config. 在asp.net中,您可以通过在web.config中添加命名空间来执行此操作。 Is there a way to do this for class files as well? 有没有办法为类文件执行此操作?

No. It is not possible to add a global using declaration to a C# project. 不可以。无法向C#项目添加全局using声明。 You must specify the complete set of using in each .cs file 您必须在每个.cs文件中指定完整的using

It's not possible to do what you want with obvious functionality but you could create a template that you generate your classes from and do that by namespace, the templates could include the using and this would give you the desired effect. 使用显而易见的功能无法实现您想要的功能,但您可以创建一个模板,您可以通过命名空间生成类,模板可以包含使用,这将为您提供所需的效果。

You could do this with basic T4 templates or something like resharper also has this functionality. 您可以使用基本的T4模板执行此操作,或者像resharper也可以使用此功能。

However it is a bit pointless, lots of productivity tools will bring in the using statements you need given code you write, resharper and others do this, so it is not neccessary to have a template that does this as you may end up in each namespace not using the declaration then find yourself having to delete it ! 然而,它有点无意义,许多生产力工具会带来您需要的使用语句,因为您编写的代码,resharper和其他人都这样做,所以没有必要有一个模板来执行此操作,因为您可能最终在每个命名空间中不使用声明然后发现自己必须删除它!

Theres not really an issue with having using statements that are unused by the way its just messy. 使用那些因其杂乱无章的方式而未被使用的语句并不是真正的问题。

Ooh just in case you aren't sure what t4 templating is here is a quick link 哦,以防你不确定这里的 t4模板是一个快速链接

我不相信这是开箱即用的,但你可以自动使用Visual Studio插件或Code Rush等工具的插件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM