C#命名空间别名限定符(::) VS对其操作()。 [英] C# Namespace Alias qualifier (::) vs Dereferencing Operator (.)

查看:141
本文介绍了C#命名空间别名限定符(::) VS对其操作()。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速和简单的问题。我有点明白了命名空间别名预选赛做什么,它是在一个命名空间访问成员,但是所以没有对其操作。我真的感到困惑,在这种情况下,为什么要使用一个比其他或不同的,他们每个如何完成同样的事情。

 使用colAlias​​ System.Collections中=; 

命名空间myns名字
{
类TestApp
{
静态无效的主要()
{
colAlias​​.Hashtable测试=新colAlias​​.Hashtable();
colAlias​​ :: Hashtable的测试1 =新colAlias​​ ::的Hashtable();
}
}
}


解决方案

这是一个极端例子(如 @ 字头)是否有应对相当极少数情况下在那里命名空间,类和关键字之间的名称冲突。



仅适用于命名空间(和命名空间别名),而。同时适用于命名空间和子类。大多数地方,你需要它,你会更好使用不同的名称代替,但并不总是一个选项。



全球:: 是最经常出现在自动生成的代码的特殊情况 - 它重置引用的命名空间根



有关实例,假设您自动生成一些代码(也许对于表单应用程序,EF,或类似)和你的应用程序使用的命名空间 YourCompany.Application 。现在,你的客户(使用自动生成)的一个决定添加自己的命名空间,在其应用 TheirCompany.YourCompany.Application 。现在所有的的自动代码,因为当它编译.NET不知道是否要使用你的命名空间或他们的失败。



要解决这个问题产生与代码::全球YourCompany.Application ,那么那些使用自动生成可以使用任何空间,他们喜欢和不冲突。



我认为微软加入全球:: ,因为他们预计一些的.Net客户添加的命名空间,比如系统


Quick and simple question. I kind of understand what the Namespace Alias qualifier does, it's for accessing members in a namespace, however so does the dereferencing operator. I am really baffled as to the difference in this situation, why you would use one over the other, or how they each accomplish the same thing.

using colAlias = System.Collections;

namespace myns
{
    class TestApp
    {
        static void Main()
        {
            colAlias.Hashtable test = new colAlias.Hashtable();
            colAlias::Hashtable test1 = new colAlias::Hashtable();
        }
    }
}

解决方案

This is a corner case :: (like the @ prefix) is there to deal with the fairly rare occurrences where a name conflicts between namespaces, classes and keywords.

:: only works for namespaces (and namespace aliases), while .. works for both namespaces and subclasses. Most places where you'd need it you'd be better off using a different name instead, but that isn't always an option.

global:: is a special case that's most often seen in auto-generated code - it resets the referenced namespace to the root.

For instance, suppose you auto-generate some code (maybe for a forms app, EF, or similar) and your app uses the namespace YourCompany.Application. Now one of your customers (using your auto-generation) decides to add their own namespace in their app TheirCompany.YourCompany.Application. Now all your auto code fails because when it compiles .Net doesn't know whether to use your namespace or theirs.

To fix this generate code with global::YourCompany.Application, then those that use your auto-generator can use whatever namespace they like and not conflict.

I think Microsoft added global:: because they expected some .Net customers to add namespaces like System.

这篇关于C#命名空间别名限定符(::) VS对其操作()。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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