C# 命名空间别名 - 有什么意义?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/505262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# namespace alias - what's the point?
提问by Brad
I have been trying to learn more about the C# language, but I haven't been able to see a situation where one would use namespace aliasing like
我一直在努力学习有关 C# 语言的更多信息,但我一直无法看到人们会使用命名空间别名的情况,例如
using someOtherName = System.Timers.Timer;
It seems to me that it would just add more confusion to understanding the language.
在我看来,这只会增加理解语言的混乱。
Could someone please explain?
有人可以解释一下吗?
采纳答案by Marc Gravell
That is a type alias, not a namespace alias; it is useful to disambiguate - for example, against:
那是一个类型别名,而不是一个命名空间别名;消除歧义是有用的 - 例如,反对:
using WinformTimer = System.Windows.Forms.Timer;
using ThreadingTimer = System.Threading.Timer;
(ps: thanks for the choice of Timer
;-p)
(ps:感谢您选择Timer
;-p)
Otherwise, if you use both System.Windows.Forms.Timer
and System.Timers.Timer
in the same file you'd have to keep giving the full names (since Timer
could be confusing).
否则,如果您在同一个文件中同时使用System.Windows.Forms.Timer
和System.Timers.Timer
,则必须继续提供全名(因为Timer
可能会造成混淆)。
It also plays a part with extern
aliases for using types with the same fully-qualified type name from different assemblies - rare, but useful to be supported.
它还与extern
别名一起发挥作用,用于使用来自不同程序集的具有相同完全限定类型名称的类型 - 很少见,但支持它很有用。
Actually, I can see another use: when you want quick access to a type, but don't want to use a regular using
because you can't import some conflicting extension methods... a bit convoluted, but... here's an example...
实际上,我可以看到另一个用途:当您想快速访问类型,但不想使用常规类型时,using
因为您无法导入一些相互冲突的扩展方法……有点令人费解,但是……这是一个示例...
namespace RealCode {
//using Foo; // can't use this - it breaks DoSomething
using Handy = Foo.Handy;
using Bar;
static class Program {
static void Main() {
Handy h = new Handy(); // prove available
string test = "abc";
test.DoSomething(); // prove available
}
}
}
namespace Foo {
static class TypeOne {
public static void DoSomething(this string value) { }
}
class Handy {}
}
namespace Bar {
static class TypeTwo {
public static void DoSomething(this string value) { }
}
}
回答by Sean Bright
It is very useful when you have multiple classes with the same name in multiple included namespaces. For example...
当您在多个包含的命名空间中有多个具有相同名称的类时,它非常有用。例如...
namespace Something.From.SomeCompanyA {
public class Foo {
/* ... */
}
}
namespace CompanyB.Makes.ThisOne {
public class Foo {
/* ... */
}
}
You can use aliases to make the compiler happy and to make things more clear for you and others on your team:
您可以使用别名使编译器满意,并使您和您团队中的其他人更清楚:
using CompanyA = Something.From.CompanyA;
using CompanyB = CompanyB.Makes.ThisOne;
/* ... */
CompanyA.Foo f = new CompanyA.Foo();
CompanyB.Foo x = new CompanyB.Foo();
回答by bdukes
I always use it in situations like this
我总是在这样的情况下使用它
using Utility = MyBaseNamespace.MySubNamsepace.Utility;
where Utility
would otherwise have a different context (like MyBaseNamespace.MySubNamespace.MySubSubNamespace.Utility
), but I expect/prefer Utility
to always point to that one particular class.
其中,Utility
否则将有一个不同的环境(如MyBaseNamespace.MySubNamespace.MySubSubNamespace.Utility
),但我希望/喜欢Utility
总是指向一个特定的类。
回答by annakata
Brevity.
简洁。
There are fringe benefits to provide clarity between namespaces which share type names, but essentially it's just sugar.
在共享类型名称的命名空间之间提供清晰度有附带好处,但本质上它只是糖。
回答by BenAlabaster
I use it when I've got multiple namespaces with conflicting sub namespaces and/or object names you could just do something like [as an example]:
当我有多个具有冲突的子命名空间和/或对象名称的命名空间时,我会使用它,您可以执行类似 [作为示例] 的操作:
using src = Namespace1.Subspace.DataAccessObjects;
using dst = Namespace2.Subspace.DataAccessObjects;
...
src.DataObject source = new src.DataObject();
dst.DataObject destination = new dst.DataObject();
Which would otherwise have to be written:
否则必须写成:
Namespace1.Subspace.DataAccessObjects.DataObject source =
new Namespace1.Subspace.DataAccessObjects.DataObject();
Namespace2.Subspace.DataAccessObjects.DataObject dstination =
new Namespace2.Subspace.DataAccessObjects.DataObject();
It saves a ton of typing and can be used to make code a lot easier to read.
它节省了大量的输入,可用于使代码更易于阅读。
回答by M4N
We have defined namespace aliases for all of our namespaces. This makes it very easy to see where a class comes from, e.g:
我们为所有命名空间定义了命名空间别名。这使得很容易看到一个类的来源,例如:
using System.Web.WebControls;
// lots of other using statements
// contains the domain model for project X
using dom = Company.ProjectX.DomainModel;
// contains common web functionality
using web = Company.Web;
// etc.
and
和
// User from the domain model
dom.User user = new dom.User();
// Data transfer object
dto.User user = new dto.User();
// a global helper class
utl.SomeHelper.StaticMethod();
// a hyperlink with custom functionality
// (as opposed to System.Web.Controls.HyperLink)
web.HyperLink link = new web.HyperLink();
We have defined some guidelines how the aliases must be named and everyone is using them.
我们已经定义了一些如何命名别名以及每个人都在使用它们的指南。
回答by Joel Mueller
In addition to the examples mentioned, type aliases (rather than namespace aliases) can be handy when repeatedly referring to generic types:
除了上面提到的例子之外,当重复引用泛型类型时,类型别名(而不是命名空间别名)会很方便:
Dictionary<string, SomeClassWithALongName> foo = new Dictionary<string, SomeClassWithALongName>();
private void DoStuff(Dictionary<string, SomeClassWithALongName> dict) {}
Versus:
相对:
using FooDict = Dictionary<string, SomeClassWithALongName>;
FooDict foo = new FooDict();
private void DoStuff(FooDict dict) {}
回答by Charlie
I find the aliases very useful in unit testing. When you are writing unit tests, it is a common practice to declare the subject to test as
我发现别名在单元测试中非常有用。在编写单元测试时,通常的做法是将要测试的主题声明为
MyClass myClassUT;
being myClassUT
the subject Under Test. But what if you want to write unit tests for a static class with static methods? Then you can create an alias like this:
作为myClassUT
主题ü的nDer牛逼EST。但是如果你想要编写单元测试与静态方法静态类?然后你可以创建一个这样的别名:
using MyStaticClassUT = Namespace.MyStaticClass;
Then you can write your unit tests like this:
然后你可以像这样编写单元测试:
public void Test()
{
var actual = MyStaticClassUT.Method();
var expected = ...
}
and you never loose sight of what the subject under test is.
并且您永远不会忘记测试的主题是什么。
回答by RBT
In one way it is really handy while coding in Visual Studio.
一方面,它在 Visual Studio 中编码时非常方便。
Use-case: Let's say I've to use only few classes e.g. SqlConnection
from a namespace System.Data
. In normal course I'll import the System.Data.SqlClient
namespace at the top of the *.cs file as shown below:
用例:假设我只使用几个类,例如SqlConnection
来自命名空间的类System.Data
。在正常情况下,我将System.Data.SqlClient
在 *.cs 文件顶部导入命名空间,如下所示:
using System.Data;
Now look at my intellisense. It is heavily proliferated with whole lot of classes to choose from while typing in code editor. I'm not going to use whole bunch of classes at all:
现在看看我的智能感知。在代码编辑器中打字时,大量的类可供选择。我根本不会使用一大堆类:
So I would rather use an alias at the top of my *.cs file and get a clear intellisense view:
所以我宁愿在我的 *.cs 文件顶部使用别名并获得清晰的智能感知视图:
using SqlDataCon = System.Data.SqlClient.SqlConnection
Now look at my intellisense view. It is super-clear and super-clean.
现在看看我的智能感知视图。它超级清晰,超级干净。
回答by Zv_oDD
One reason I know; It lets you use shorter names when you have name collisions from imported namespaces. Example:
我知道的一个原因;当导入的命名空间发生名称冲突时,它允许您使用较短的名称。例子:
If you declared using System.Windows.Forms;
and using System.Windows.Input;
in the same file when you go to access ModifierKeys
you might find that the name ModifierKeys
is in both the System.Windows.Forms.Control
and System.Windows.Input
namespaces.
So by declaring using Input = System.Windows.Input;
you can then get System.Windows.Input.ModifierKeys
via Input.ModifierKeys
.
如果您 在访问时在同一个文件中声明using System.Windows.Forms;
and using System.Windows.Input;
,ModifierKeys
您可能会发现该名称ModifierKeys
同时在 theSystem.Windows.Forms.Control
和System.Windows.Input
命名空间中。因此,通过声明,using Input = System.Windows.Input;
您可以System.Windows.Input.ModifierKeys
通过Input.ModifierKeys
.
I'm not a C# buff but aliasing namespace seems like "best practise" to me. That way you know what you're getting and still don't have to type too much more.
我不是 C# 爱好者,但别名命名空间对我来说似乎是“最佳实践”。这样你就知道你得到了什么,而且仍然不必输入太多。