没有任何内置功能可以做到这一点(绑定到构造函数)。我不确定你为什么要避免 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));
}