如何将扩展方法作为参数传递给类的构造函数,并且该类中的方法是否将该扩展名用作扩展名?
例如:这是一个包含IEnumerable扩展方法的文件:
namespace System.Collections.Generic
{
public static partial class IEnumerableMethodExtensions
{
/// <summary>
/// Used by IsImageFile to determine if a file is a graphic type
/// we care about. (Not an Extension Method, just a helper method)
/// </summary>
public static string[] GraphicFileExtensions = new string[] { ".png", ".bmp", ".gif", ".jpg", ".jpeg" };
/// <summary>
/// Method Extension - specifies that FileInfo IEnumerable should only
/// return files whose extension matches one in GraphicFileExtensions[].
/// </summary>
/// <param name="files"></param>
/// <returns></returns>
public static IEnumerable<FileInfo> IsImageFile(this IEnumerable<FileInfo> files)
{
foreach (FileInfo file in files)
{
string ext = file.Extension.ToLower();
if (GraphicFileExtensions.Contains(ext))
yield return file;
}
}
}
}
我希望能够将IsImageFile()作为参数传递给此对象的构造函数,以便该类中的方法可以将IsImageFile用作方法扩展:
public class MainFileInfoSource
{
public MainFileInfoSource(List<DirectoryInfo> Directories,
ENUMERABLE_METHOD_EXTENSION_FILE_FILTER TheMethodExtension)
{
_myFilterMethodExtension = TheMethodExtension;
_directories = Directories;
initializeFileInfoList();
}
...
/// <summary>
/// Initializes the Files list.
/// </summary>
private void initializeFileInfoList()
{
...
for (int i = 0; i < _directories.Count; i++)
{
iEnumerableFileInfo = new[] { _directories[i] }.Traverse(dir =>
getDirectoryInfosWithoutThrowing(dir)).SelectMany(dir =>
getFileInfosWithoutThrowing(dir)._myFilterMethodExtension());
答案 0 :(得分:3)
如何将扩展方法作为参数传递给类的构造函数??
使参数成为与您正在寻找的签名匹配的委托。例如,Func<IEnumerable<FileInfo>, IEnumerable<FileInfo>>
适用于您提供的案例。
public MainFileInfoSource(List<DirectoryInfo> Directories,
Func<IEnumerable<FileInfo>, IEnumerable<FileInfo>> FilterMethod)
请注意,在这种情况下,您必须使用其静态位置或使用lambda表达式来标识方法:
var source = new MainFileInfoSource(directories, FileFilterExtensions.IsAwesome);
var source2 = new MainFileInfoSource(directories, f => f.IsAwesome());
...,并且该类中的方法是否将该扩展用作扩展名?
这不可能。扩展方法只是特殊的语法糖,并且有很多关于如何使用它们的规则。从扩展方法创建委托时,不会传输此信息。因此,您必须将委托称为常规方法。
iEnumerableFileInfo = new[] { _directories[i] }
.Traverse(dir => getDirectoryInfosWithoutThrowing(dir))
.SelectMany(dir => _myFilterMethod(getFileInfosWithoutThrowing(dir)));
答案 1 :(得分:0)
它不适合你吗?
public class MainFileInfoSource
{
public MainFileInfoSource(List<DirectoryInfo> Directories,
Func<IEnumerable<FileInfo>, IEnumerable<FileInfo>> TheMethodExtension)
{
}
}
和
new MainFileInfoSource(null, IEnumerableMethodExtensions.IsImageFile);