Namespace references in C# vs. VB.Net

99封情书 提交于 2019-12-18 21:53:54

问题


In VB.Net you can do something like the following without any issues... just ignore the fact that this is a pretty useless class :-)


Imports System

Public Class Class1
    Public Shared Function ArrayToList(ByVal _array() As String) As Collections.Generic.List(Of String)
        Return New Collections.Generic.List(Of String)(_array)
    End Function
End Class

However if you do the same thing in C#...


using System;

public class Class1
{
    public static Collections.Generic.List ArrayToList(string[] _array)
    {
        return new Collections.Generic.List(_array);
    }
}

You will get an error on the line with the return on "Collections.Generic.List" saying "The type or namespace name 'Collections' could not be found (are you missing a using directive or an assembly reference?)"

I know that you have to actually have a using directive to System.Collections.Generic to use List but I don't know why. I also don't understand why I don't get the same error in the function declaration, but only in the return statement.

I was hoping someone can explain this or even refer me to a technet page that explains it. I have searched around, but can't find anything that explains this concept.

Edit: Just to note, the question is really about the referencing of a sub-namespace such as in the example being able to reference Collections within System.


回答1:


using directive in C# does not allow this:

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.

VB.NET, however, supports somewhat closer behavior with Imports statement:

The scope of the elements made available by an Imports statement depends on how specific you are when using the Imports statement. For example, if only a namespace is specified, all uniquely named members of that namespace, and members of modules within that namespace, are available without qualification. If both a namespace and the name of an element of that namespace are specified, only the members of that element are available without qualification.

Reference SO Question




回答2:


This is because VB.Net supports partial namespaces; C# does not.

With Visual Basic, System is imported by default and child namespaces are automatically resolved.

Read more in this article.

VB.Net vs C#, Round 2: Partial Namespaces




回答3:


you can say System.Collections.Generic.List. that would work.

I think you need to give the entire list and not omit out the system part.

ALso you will need to template it with string as in List similar to the List(Of string)



来源:https://stackoverflow.com/questions/1315256/namespace-references-in-c-sharp-vs-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!