vb.net中collection如何转换到C#
Dim d As New Collection
d.Add( "Northsnow ")
d.Add( "塞北的雪 ")
d.Add( "http://blog.csdn.net ")
Dim t As New ArrayList(d)
Dim sb As New System.Text.StringBuilder()
If t.Count > 0 Then
sb.Append( "ArrayList中共有 成员 ")
sb.Append(t.Item(2).ToString)
sb.Append( " 个 ")
For Each aa As String In t
sb.AppendLine()
sb.Append(aa)
Next
End If
MsgBox(sb.ToString)
以上是使用ARRAYLIST存储一个集合,VB中可以使用collectin,将其传入arraylist,而在C#中如何定义这个东西,使他能够传入ARRAYLIST呢?给个例子,谢谢
[解决办法]
1。
// 事实上你可以直接在 C# 中使用 Microsoft.VisualBasic.Collection
// 需要添加对 Microsoft.VisualBasic.dll 的引用
Microsoft.VisualBasic.Collection d = new Microsoft.VisualBasic.Collection();
d.Add( "Northsnow ", null, null, null); // C# 不支持可选参数, 若不指定 传入 null
d.Add( "塞北的雪 ", null, null, null);
d.Add( "http://blog.csdn.net ", null, null, null);
ArrayList t = new ArrayList(d);
StringBuilder sb = new System.Text.StringBuilder();
if (t.Count > 0) {
sb.Append( "ArrayList中共有 成员 ");
sb.Append(t.Count.ToString());
sb.Append( " 个 ");
}
foreach (string aa in t) {
sb.AppendLine();
sb.Append(aa);
}
2。
以上代码比较适合将进行 VB.net 向 C# 的直接移植,
因为
Visual Basic 集合与 System.Collections、System.Collections.Generic 和 System.Collections.Specialized 命名空间中的 .NET Framework 集合不兼容
具体没有实践过,不知道是否会导致后期维护的困难。
3。
若新项目,最佳实践实现是,使用 System.Collection.ArrayList
ArrayList list1 = new ArrayList();
list1.Add( "a ");
list1.Add( "b ");
ArrayList list2 = new ArrayList(list1);