我正在处理对象之间现有的稍微复杂的关系。为了便于理解,进行了一些重构之后,我的代码现在看起来像这样:
TemplateColorList colors = new TemplateColorList();
var template = new Template {
TextElements = CreateTextElements(textElementData,
/* -> */ (textElement, colorParam1, colorParam2) => colors.AddTextColor(textElement, colorParam1, colorParam2)
),
ClipArtElements = CreateClipArtElements(clipArtElementData,
/* -> */ (clipArtElement, colorParam) => colors.AddClipArtColor(clipArtElement, colorParam)
),
Colors = colors,
};
我看到可以消除的重复项,但是-代表只是按原样将参数传递给colors
方法。 是否可以通过实例方法(非静态)创建委托而不重复参数?
答案 0 :(得分:1)
将评论转换为答案...
“没有这个额外的委托,就不是CreateTextElements(textElementData,colors.AddTextColor)吗?” -@WiktorZychla
“如果您曾经在方法调用中忘记了括号,则可能会遇到编译器错误:无法将方法组转换为某些东西。这是相反的。现在,您要引用没有括号的方法或参数,因为方法是参数。” -@ScottHannen(重点是我的)
感谢您的帮助!我错误地认为这些类型在这里不可行。根据他们的建议,我的代码现在看起来像:
TemplateColorList colors = new TemplateColorList();
var template = new Template {
TextElements = CreateTextElements(textElementData, colors.AddTextColor),
ClipArtElements = CreateClipArtElements(clipArtElementData, colors.AddClipArtColor),
Colors = colors,
};