为什么类似的命名空间类不共享 using 指令? [英] Why don't similar namespaced classes share using directives?

查看:36
本文介绍了为什么类似的命名空间类不共享 using 指令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将新类添加到命名空间时,这就是我得到的(这是在 mvc3 项目中)

When adding a new class into a namespace this is what I get (this is in an mvc3 project)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Foo.Models
{
 public class Bar
 {
 }
}

在命名空间 Foo.Models 中还有其他类.但是,通过将内容放置在不同的 .cs 位置来分隔内容是很好的.我认为这是相当标准的.我知道编译器无论如何都会发挥它的魔力来组合所有这些.这就是我的问题的来源.如果命名空间是稍后组成的,那么为什么需要始终重新定义类正在使用的内容?如果它已经在命名空间中的某处可用,那么是否有必要在每个 .cs 文件中说 using System; 定义命名空间内的类?有人可以为我解释一下这一点,也许还可以阐明一种可能的方法来实现这一点,即我为命名空间定义所有用例一次,然后添加到该命名空间的任何类本质上都可以访问

In the namespace Foo.Models there are other classes. However, it is nice to separate content by placing them in different .cs locations. I think that is fairly standard. I know the compiler works its magic to compose all these later anyway. Which is kind of where my question arose from. If the namespace is composed later on, then why is there a requirement to always be redefining what the class is using? If it is already available somewhere in the namespace, then should it be necessary to say using System; in every .cs file defining a class inside of the namespace? Can someone explain this a little for me, and also perhaps shed some light on a possible way to do implement this in a way where I define all of the using cases for a namespace once and then any classes added to that namespace inherently have access to those.

推荐答案

using 语句的范围仅限于您正在使用的特定 .cs 文件.

The using statements are scoped to the particular .cs file you are working with.

它们只是在该类文件的上下文中提供了一个方便的快捷方式,允许您仅使用类的名称,而不是在您使用它们的任何地方完全限定类名称.

They simply provide a convenient shortcut in the context of that class file that allows you to use the names of classes only, rather than fully qualifying class names everywhere you use them.

命名空间的存在是因为不同的团队不可避免地会对不同的类使用相同的类名(我想知道有多少个 Util 类).

Namespaces exist because different teams will inevitably use the same class name for different classes (I wonder how many Util classes are out there).

您的项目中可能有两个不同的类想要使用具有相同名称的不同对象.在每个文件中使用不同的 using 语句的能力让您可以方便地做到这一点.

You may have two different classes in your project that want to use different objects with the same name. The ability to have different using statements in each file lets you do that conveniently.

请注意,您始终可以编辑新类的模板,以预先填充所有类中所需的 using 语句.

Note that you can always edit the template for new classes to pre-populate the using statements you need in all of your classes.

这篇关于为什么类似的命名空间类不共享 using 指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆