Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

c# - Why can't i use partly qualified namespaces during object initialization?

I suspect this is a question which has been asked many times before but i haven't found one.

I normally use fully qualified namespaces if i don't use that type often in the file or i add using namaspacename at the top of the file to be able to write new ClassName().

But what if only a part of the full namespace was added ? Why can't the compiler find the type and throws an error?

Consider following class in a nested namespace:

namespace ns_1
{
    namespace ns_1_1
    {
        public class Foo { }
    }
}

So if i now want to initialize an instance of this class, it works in following ways:

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();
    }
}

But following doesn't work:

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();
    }
}

it throws the compiler error:

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

I assume because ns_1_1 is treated like a class which contains another class Foo instead of a namespace, is this correct?

I haven't found the language specification, where is this documented? Why is the compiler not smart enough to check if there's a class or namespace(-part)?


Here's another - less abstract - example of what i mean:

using System.Data;

public class Program
{
    public Program()
    {
        using (var con = new SqlClient.SqlConnection("...")) // doesn't work
        {
            //... 
        }
    }
}

Edit: now i know why this seems very strange to me. It works without a problem in VB.NET:

Imports System.Data

Public Class Program
    Public Sub New()
        Using con = New SqlClient.SqlConnection("...") ' no problem

        End Using
    End Sub
End Class
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This obvious way unfortunately not working but you can make all this by an alias namespace:

using ns_1_1 = ns_1.ns_1_1;

public class Program
{
    public Program()
    {
        var no_foo = new ns_1_1.Foo();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...