在通用方法内将未知参数添加到Func [英] Add unknown parameter to a Func inside a generic method
问题描述
我在网上查看了许多资源,但我认为这是不可能的,或者我是从错误的角度进行研究的.
I have looked at many resources online but I think this is something not possible or I am approaching it from the wrong angle.
我正在从子表中生成ID列表,并确定父表中的外键ID是否包含在子ID列表中.例如j =>!ids.Contains(j.InvestorId).下面的代码将无法编译,因为whereFilter无法接受参数,但是您可以看到我想要的效果.
I am generating a list of ids from a child table and determining if the foreign key id in the parent table contains in the list of child ids. e.g. j => !ids.Contains(j.InvestorId). The code below will not compile as whereFilter can not take a parameter but you can see the effect I would like.
希望有一种方法可以代替预先获取id并将附加参数传递给whereFilter.
Hopefully, there is a way instead of getting the ids beforehand and passing in an additional parameter to whereFilter.
public List<int> ValidateReferentialIntegrity<TChild, TParent>(string childFilePath,
string parentFilePath,
Func<TParent, int, bool> whereFilter,
Func<TParent, int> selector)
{
var childList = ReadCsvFile<TChild>(typeof(TChild).Name, childFilePath);
var parentList = ReadCsvFile<TParent>(typeof(TParent).Name, parentFilePath);
var ids = childList.Select(s => (int)s.GetId()).ToList();
var unidentifiableIds = parentList.Where(whereFilter(ids))
.Select(selector).ToList();
return unidentifiableIds;
}
推荐答案
public List<int> ValidateReferentialIntegrity<TChild, TParent>(string childFilePath,
string parentFilePath,
Func<TParent, IList<int>, bool> whereFilter, // <- change #1 is here, IList<int>
Func<TParent, int> selector)
{
var childList = ReadCsvFile<TChild>(typeof(TChild).Name, childFilePath);
var parentList = ReadCsvFile<TParent>(typeof(TParent).Name, parentFilePath);
var ids = childList.Select(s => (int)s.GetId()).ToList();
var unidentifiableIds = parentList
.Where(p => whereFilter(p, ids)) // <- change #2 is here, pass object to whereFilter
.Select(selector)
.ToList();
return unidentifiableIds;
}
并这样称呼它:
var list = ValidateReferentialIntegrity<TChild, TParent>(
"file1.csv",
"file2.csv",
(TParent parent, IList<int> childIds) => childIds.Contains(parent.InvestorId),
parent => parent.InvestorId);
这篇关于在通用方法内将未知参数添加到Func的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!