1

这是我编写的将逗号列表转换为 T 数组的片段:

public static T[] ToArray<T>(this string s, params char[] seps)
{
    if (typeof(T) == typeof(int))
    {
        return s.Split(seps.Length > 0 ? seps : new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(id => int.Parse(id))
                    .Cast<T>()
                    .ToArray();
    }
    else throw new Exception("cannot convert to " + typeof(T).Name);
}

我需要为我想要支持的每种类型设置一个案例。

有没有更好的方法来编码这种东西?

4

3 回答 3

4

你总是可以做这样的事情:

public static T[] ToArray<T>(this string s, Func<string, T> converter, params char[] seps)
{
    return s.Split(seps.Length > 0 ? seps : new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
            .Select(converter)
            .ToArray();
}

你可以这样称呼:

"1,2,3".ToArray(int.Parse, ',', ';');

我同意 .Parse 有点难看,但它为您提供了您想要的任何数据类型的灵活性......

于 2012-08-21T00:44:30.370 回答
2

如果你限制TIConvertible,你可以使用ToType

public static T[] ToArray<T>(this string s, params char[] seps)
   where T : IConvertible
{
    Type targetType = typeof(T);
    return s.Split(seps.Length > 0 ? seps : new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                    .Cast<IConvertible>()
                    .Select(ic => ic.ToType(targetType, CultureInfo.InvariantCulture))
                    .Cast<T>()
                    .ToArray();
}
于 2012-08-21T00:45:45.080 回答
0

你可以试试:

public static T[] ToArray<T>(this string s, Func<string, T> convert, char[] seps)
{
  char[] separators = seps != null && seps.Length > 0 ? seps : new[] { ',' };
  T[]    values     = s.Split(separators, StringSplitOptions.RemoveEmptyEntries)
                       .Select(x => convert(x))
                       .ToArray()
                       ;
  return values;
}

只需传入一个委托来进行转换:

int[] Xs = "1,2,3".ToArray<int>(int.Parse , ',' , '-' , '/' , '|');
于 2012-08-21T00:52:13.597 回答