首页 > 解决方案 > 将 VB6 err 对象的用法转换为 C#

问题描述

下面是我的 vb6 代码如何将其转换为 c#,实际上我在 if 条件下处理错误时感到困惑。

Function FilterDuplicates(Arr As Variant) As Long
Dim col As Collection, Index As Long, dups As Long
Set col = New Collection
On Error Resume Next
For Index = LBound(Arr) To UBound(Arr)
    col.Add 0, CStr(Arr(Index))
    If err Then
        Arr(Index) = Empty
        dups = dups + 1
        err.Clear
    ElseIf dups Then
        Arr(Index - dups) = Arr(Index)
        Arr(Index) = Empty
    End If
Next
FilterDuplicates = dups      End Function

下面是我尝试过的 C# 代码,实际上我无法处理这个 If 条件部分。

        private long FilterDuplicates(string[] Arr)
    {
        Collection col = new Collection();
        long Index=0;
        long dups =0;    
        try
        {
            for (Index = Arr.GetLowerBound(0); Index <= Arr.GetUpperBound(0); Index++)
            {
                col.Add(0, Conversion.Str(Arr[Index]));
                if (Information.Err)
                {
                    Arr[Index] = null;
                    dups += 1;
                    err.Clear;
                }
                else if (dups != 0)
                {
                    Arr[Index - dups] = Arr[Index];
                    Arr[Index] = null;
                }
            }
            return dups;
        }
        catch
        {

        }
    }

标签: c#vb6migration

解决方案


通常实现例程比转换它更容易。看来,你想要

  1. 将每个重复项(即第二个、第三个等值)更改为null
  2. 计算所有这些变化

如果是你的情况,你可以试试

 private static long FilterDuplicates(string[] Arr) {
   HashSet<string> appeared = new HashSet<string>();

   long result = 0;  

   for (int i = 0; i < Arr.Length; ++i)       
     if (!appeared.Add(Arr[i])) {
       result += 1;

       Arr[i] = null;
     }

   return result;
 }

推荐阅读