我必须为所有类型的静态数组创建ToDynamic()
函数,它返回一个新的动态列表,该列表由调用函数的数组元素组成(就像ToList()
一样),就像这样:
int [] x = {1,2,3,4};
List<int> arr = x.ToDynamic();
答案 0 :(得分:1)
你可以使用x.ToList()
做你想做的事。如果你真的想自己实现它,你可以写一个通用的扩展方法,如下所示:
public static class ArrayExtensions
{
public static List<T> ToDynamic<T>(this T[] items)
=> new List<T>(items ?? throw new ArgumentNullException(nameof(items)));
}
答案 1 :(得分:0)
扩展方法编写的方案是
// partial: often we have many extensions on collections (Tree, Aggregations etc.)
// which are implemented in different files
public static partial class EnumerableExtensions {
// IEnumerable<T> - choose argument's type being as much generic and basic as you can
public static List<T> ToDinamic<T>(this IEnumerable<T> source) {
// Validate argument(s)
if (null == source)
throw new ArgumentNullException(nameof(source)); // or return null or empty list
return new List<T>(source);
}
}