Función genérica de C#, no se puede convertir

programación


Tengo esta función C#

C#
internal static SortedList<string, string> doSList(string list)
        {
            SortedList<string, string> ret = new SortedList<string, string>();

            char[] charSeparators = new char[] { '|' };
            string[] l1 = list.Split('|');
            if (l1.Count() > 0)
            {
                foreach (string ll1 in l1)
                {
                    string[] l2 = ll1.Split(';');

                    if (l2.Count() == 2)
                    {
                        {
                            //ret.Add(Convert.ChangeType(l2[0], typeof(key)), Convert.ChangeType(l2[1], typeof(value)));
                            ret.Add(l2[0], l2[1]);
                        }
                    }
                }
            }
            return ret;
        }

entonces necesito algún tiempo después:

C#
internal static SortedList<string, int> doSList2(string list)

Lo que he probado:

Así que lo hice, pero el compañero de VB.net pudo hacerlo.

V.B.
Friend Shared Function doSList(Of key, value)(ByVal list As String) As SortedList(Of key, value)

pero no puedo hacer:

C#
<pre>internal static SortedList<TKey, TValue> doSList2(string list)

El error dice TKey no encontrada, TValue no encontrada, luego probé solo con T y luego T no encontrada.

Puede que sea una pregunta de principiante, por favor que alguien me guíe hasta esto, ¿algún enlace donde aprender?

Solución 1

Suponiendo que la clave es siempre una string ya que la entrada tiene un formato de valor separado por comas; algo parecido a esto debería funcionar.

C#
public static SortedList<string, TValue> DoSList<TValue>(string csv) where TValue : IConvertible
  {
    SortedList<string, TValue> target = new ();
     string[] firstSplitArray = csv.Split('|');
      if (firstSplitArray.Length > 0)
       {
        foreach (string t1Instance in firstSplitArray)
         {
          string[] secondSplitArray = t1Instance.Split(';');

          if (secondSplitArray.Length == 2)
           {
            {
              var result= (TValue)Convert.ChangeType(secondSplitArray[1], typeof(TValue));
              target.Add(secondSplitArray[0], result);
            }
           }
         }
       }
     return target;
   }

Se puede utilizar así: –

C#
string testStr = "Y;5|X;6|W;7|V;8|A;1|B;2|C;3|D;4";
 SortedList<string, int> sortedList = DoSList<int>(testStr);
 foreach (var kvp in sortedList)
 Console.WriteLine($"{kvp.Key}:{kvp.Value}");

コメント

タイトルとURLをコピーしました