0

有很多方法可以将字符串/列表转换为其他内容的列表。

出于好奇,我找不到是否有办法这样做

Directory.EnumerateFiles(@"C:\Drivers").ToList<FileInfo>();

或者

new List<string>(Directory.EnumerateFiles(@"C:\Drivers")).Cast<FileInfo>();`

`

由于 fileinfo 将 FileInfo(path) 作为参数,因此有一种方法可以做到这一点,或者是一个不涉及 linq Select(x => new FileInfo(x) 或类似的东西的短单行器?

4

1 回答 1

1

没有任何内置功能可以做到这一点(绑定到构造函数)。我不确定你为什么要避免 Select(x => new FileInfo(x))。但是,如果您想定义一个扩展方法,例如下面的 Construct 来执行绑定,您可以:

    static void Main(string[] args)
    {
        const string path = "d:\\";
        var results = Directory.EnumerateFiles(path).Construct<string, FileInfo>();
    }

    private static ConcurrentDictionary<Type, object> constructors = new ConcurrentDictionary<Type, object>();

    private static IEnumerable<TOutput> Construct<TInput, TOutput>(this IEnumerable<TInput> input)
    {
        var constructor = constructors.GetOrAdd(typeof(TOutput), (Type type) =>
        {
            var parameterExpression = Expression.Parameter(typeof(TInput));
            var matchingConstructor = typeof(TOutput).GetConstructor(new[] { typeof(TInput) });
            var expression = Expression.Lambda<Func<TInput, TOutput>>(Expression.New(matchingConstructor, parameterExpression), parameterExpression);
            return (object)expression.Compile();
        });

        return input.Select(x => ((Func<TInput,TOutput>)constructor)(x));
    }
于 2018-03-15T23:10:48.013 回答