c# – 为什么我不能在对象初始化期间使用部分限定的命名空间?

前端之家收集整理的这篇文章主要介绍了c# – 为什么我不能在对象初始化期间使用部分限定的命名空间?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我怀疑这是一个曾经多次被问过的问题,但我还没找到. @H_301_2@如果我不经常在文件中使用该类型,或者我使用文件顶部的namaspacename添加以便能够编写新的ClassName(),我通常使用完全限定的命名空间.

@H_301_2@但是,如果只添加了完整命名空间的一部分呢?为什么编译器找不到类型并抛出错误

@H_301_2@考虑嵌套命名空间中的以下类:

namespace ns_1
{
    namespace ns_1_1
    {
        public class Foo { }
    }
}
@H_301_2@因此,如果我现在想要初始化此类的实例,它可以通过以下方式工作:

using ns_1.ns_1_1;

public class Program
{
    public Program()
    {
        // works,fully qualified namespace:
        var foo = new ns_1.ns_1_1.Foo();
        // works,because of using ns_1.ns_1_1:
        foo = new Foo();
    }
}
@H_301_2@但是以下不起作用:

using ns_1;

public class Program
{
    public Program()
    {
        // doesn't work even if using ns_1 was added
        var no_foo = new ns_1_1.Foo();
    }
}
@H_301_2@它会抛出编译器错误

@H_301_2@The type or namespace name ‘ns_1_1’ could not be found (are you
missing a using directive or an assembly reference?)

@H_301_2@我假设因为ns_1_1被视为包含另一个类Foo而不是命名空间的类,这是正确的吗?

@H_301_2@我还没有找到语言规范,这在哪里有记录?为什么编译器不够智能来检查是否有类或命名空间(-part)?

@H_301_2@这是另一个 – 不那么抽象 – 我的意思的例子:

using System.Data;

public class Program
{
    public Program()
    {
        using (var con = new sqlClient.sqlConnection("...")) // doesn't work
        {
            //... 
        }
    }
}
@H_301_2@编辑:现在我知道为什么这对我来说似乎很奇怪.它在VB.NET中没有问题:

Imports System.Data

Public Class Program
    Public Sub New()
        Using con = New sqlClient.sqlConnection("...") ' no problem

        End Using
    End Sub
End Class

解决方法

documentation说:
@H_301_2@Create a using directive to use the types in a namespace without having to specify the namespace. A using directive does not give you access to any namespaces that are nested in the namespace you specify.

@H_301_2@因此,using仅包含在指定命名空间中定义的类型(而不是命名空间).要访问嵌套命名空间的类型,您需要使用using指令显式指定它,就像在第一个示例中一样.

原文链接:https://www.f2er.com/csharp/244753.html

猜你在找的C#相关文章