CLR 如何处理 C#、VB.Net、
我不知道如何解释我的问题,请以示例形式接受:
我用C#语言编写了一个库,其方法如下:
public object GetValueAt(int idx) {
return arr[idx];
}
然后我在VB.Net中使用它,当然C#之间基于索引的不同和VB.Net。因此,如果我使用 idx = 6 调用该方法,CLR 如何知道我尝试访问的对象(在 C# 上它具有 idx = 5)?
这只是我的例子,.Net 中现有的库怎么样?
I don't know how to explain my question, please accept it in example form:
I wrote a library in C# language which has a method as below:
public object GetValueAt(int idx) {
return arr[idx];
}
Then I use it in VB.Net, ofcourse there's a diffirent in index based between C# and VB.Net. So if I call that method with idx = 6
, how does CLR know object which I try to access (it having idx = 5
on C#)?
That's just my example, and what about existed library in .Net?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我知道您可能认为 C# 和 VB.Net 之间存在索引差异的唯一区别在于声明数组时。
在 VB.Net 中,声明数组的上限:
声明一个包含 11 个元素的数组,从 0 开始,到 10 结束。在 C# 中,声明长度数组的:
声明一个包含 10 个元素的数组,从 0 开始,到 9 结束。
具有相同索引值的索引访问在两种语言中的工作方式相同。
The only difference I'm aware of where you may believe there's an indexing difference between C# and VB.Net is when declaring an array.
In VB.Net, you declare the upper bound of the array:
declares an array with 11 elements, starting at 0, ending at 10. In C#, you declare the length of the array:
declares an array with 10 elements, starting at 0, ending at 9.
Indexed access with identical index values works the same in both languages.
如果您使用
idx = 6
从 VB 调用该方法,它将返回arr[6]
,并将arr
视为从 0 开始(即第七个元素) ),因为代码是用 C# 编写的。不应用自动变基,因为您只是从 VB 调用方法。我认为当数组索引表达式本身在VB中时,VB编译器会自动调整数组索引,但这里的情况并非如此 - 它只是一个方法调用。 编辑:看起来这种情况无论如何都不会发生,至少不会总是发生。编译器在创建数组时做出了调整,但显然没有对它们进行索引...
编辑:这与 MSDN "Visual Basic 中的数组" 页显示了示例并进行了说明:
并且来自 此博文:
If you call that method from VB with
idx = 6
it will returnarr[6]
treatingarr
as 0-based (i.e. the seventh element), because the code is written in C#. No automatic rebasing is applied, because you're just calling a method from VB.I thought the VB compiler automatically adjusts array indexes when the array indexing expression itself is in VB, but that's not the case here - it's just a method call. EDIT: It looks like that doesn't happen anyway, at least not always. The compiler makes allowances when creating arrays, but not indexing into them, apparently...
EDIT: That chimes in with the MSDN "Arrays In Visual Basic" page which shows an example and explains:
And from this blog post: