C# 与 VB.Net 中的命名空间引用
在 VB.Net 中,您可以执行类似以下操作,不会出现任何问题...只需忽略这是一个非常无用的类这一事实:-)
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
但是,如果您在 C# 中执行相同的操作...
using System;
public class Class1
{
public static Collections.Generic.List ArrayToList(string[] _array)
{
return new Collections.Generic.List(_array);
}
}
您将收到错误与“Collections.Generic.List”的返回一致,显示“找不到类型或命名空间名称“Collections”(您是否缺少 using 指令或程序集引用?)”
我知道您实际上必须有一个 using指令 System.Collections.Generic 使用 List 但我不知道为什么。我也不明白为什么我在函数声明中没有得到相同的错误,而只在 return 语句中得到同样的错误。
我希望有人可以解释这一点,甚至让我参考一个解释它的技术网页。我四处搜寻,但找不到任何可以解释这个概念的东西。
编辑:请注意,问题实际上是关于子命名空间的引用,例如在示例中能够引用 System 中的集合。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
C# 中的
using
指令 不允许这样做:然而,VB.NET 支持更接近的 使用
Imports
语句的行为:参考SO问题
using
directive in C# does not allow this:VB.NET, however, supports somewhat closer behavior with
Imports
statement:Reference SO Question
这是因为VB.Net 支持部分命名空间; C# 没有。
阅读本文了解更多内容。
VB.Net 与 C#,第 2 轮:部分命名空间
This is because VB.Net supports partial namespaces; C# does not.
Read more in this article.
VB.Net vs C#, Round 2: Partial Namespaces
你可以说System.Collections.Generic.List。那会起作用的。
我认为你需要给出整个列表,而不是省略系统部分。
另外,您需要使用类似于 List 中的字符串对其进行模板化,类似于 List(Of string)
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)