更新时间:2023-02-09 15:16:17
Oded 是对的,(对他或我而言)尝试使此方法通用似乎没有任何意义.您正在尝试泛化一个方法,该方法的功能实际上特定于几种类型.
Oded is right, it doesn't seem (to him or me) to make any sense to try and make this method generic. You are trying to genericize a method whose functionality is actually specific to a few types.
现在,这就是说,函数的 bulk 似乎与您要访问的这个属性无关.那么为什么不把它分成两部分:可以泛化的部分和不能泛化的部分:
Now, that said, it seems the bulk of the function is independent of this property you want to access. So why not split it into two parts: that which can be genericized, and that which can't:
像这样:
void BindElements<T, TProperty>(IEnumerable<T> dataObjects,
Func<T, TProperty> selector)
{
Paragraph para = new Paragraph();
foreach (T item in dataObjects)
{
// Notice: by delegating the only type-specific aspect of this method
// (the property) to (fittingly enough) a delegate, we are able to
// package MOST of the code in a reusable form.
var property = selector(item);
InlineUIContainer uiContainer = this.CreateElementContainer(property)
para.Inlines.Add(uiContainer);
}
FlowDocument flowDoc = new FlowDocument(para);
this.Document = flowDoc;
}
然后你处理特定类型的重载,例如,IPerson
,可以重用这段代码(我怀疑这可能是你一直以来的代码重用):
Then your overloads dealing with specific types, e.g., IPerson
, can reuse this code (which I suspect may be what you were after all along—code reuse):
public void BindPeople(IEnumerable<IPerson> people)
{
BindElements(people, p => p.FirstName);
}
...然后对于 IOrder
:
public void BindOrders(IEnumerable<IOrder> orders)
{
BindElements(orders, o => p.OrderNumber);
}
...等等.