关于C#和VB.net的一个语法对比问题

sieistsonne 2016-01-06 08:33:15
在vb.net中,使用如下代码不会有问题:

Dim t as String="123"
Dim i as New List(Of Integer)
i.Add(0)
Integer.TryParse(t,i(0))

运行之后,最后一句会把t转换成Integer型,并赋值给i中的第一个元素,于是最后的效果是i(0)的值变为123。没问题。

而翻译成C#,如下:

String t = "123";
List<Int> i = new List<Int>();
i.add(0);
Int.TryParse(t,out i[0]);

编译不通过,最后一句报错:“属性或索引器不得作为 out 或 ref 参数传递”。

如果改成这样,则没问题了:

String t = "123";
Int[] i = new Int[1];
i[0]=0;
Int.TryParse(t,out i[0]);

所以我有两个问题:
1、为什么C#第一段代码使用List表就不能用在out后面,而第二段代码中使用数组就可以?
2、VB.net也是用List,为什么就可以?是VB.net与C#在这个语句上的编译处理有所不同吗?还是他们两个所用的TryParse根本就是两个不同的函数??

请高人解答!不胜感谢!
...全文
159 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
masanaka 2016-01-06
  • 打赏
  • 举报
回复
引用 1 楼 shingoscar 的回复:
1,list后面带方括号是索引器,其实就是写法特别的属性,本质上是一个函数,所以不能直接作为out的参数 数组后面带括号是c#内建的语法,是一个值,所以没问题 2,VB里的写法你可以认为是语法糖,最终编译出来的结果可以看到加了一堆临时变量来处理这个问题
Dim t As String = "123"
Dim i As List(Of Integer) = New List(Of Integer)()
i.Add(0)
Dim arg_23_0 As String = t
Dim list As List(Of Integer) = i
Dim arg_1A_0 As List(Of Integer) = list
Dim index As Integer = 0
Dim value As Integer = arg_1A_0(index)
Integer.TryParse(arg_23_0, value)
list(index) = value
threenewbee 2016-01-06
  • 打赏
  • 举报
回复
简单来说,你可以认为VB比较“智能”。但是这种“智能”会给你写程序增加很多不好的习惯。
Poopaye 2016-01-06
  • 打赏
  • 举报
回复
1,list后面带方括号是索引器,其实就是写法特别的属性,本质上是一个函数,所以不能直接作为out的参数 数组后面带括号是c#内建的语法,是一个值,所以没问题 2,VB里的写法你可以认为是语法糖,最终编译出来的结果可以看到加了一堆临时变量来处理这个问题
Dim t As String = "123"
Dim i As List(Of Integer) = New List(Of Integer)()
i.Add(0)
Dim arg_23_0 As String = t
Dim list As List(Of Integer) = i
Dim arg_1A_0 As List(Of Integer) = list
Dim index As Integer = 0
Dim value As Integer = arg_1A_0(index)
Integer.TryParse(arg_23_0, value)
list(index) = value

111,129

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧