我有以下方法,我想知道下面是否有任何可以放在 default(void) 的地方,因为有一个编译器错误表明 void 在这里无效:
private void applyDefaultsIfNecessary(ApplicationConfiguration configuration)
{
var defaults = new Dictionary<Predicate<ApplicationConfiguration>, Action<ApplicationConfiguration>>()
{
// { rule, action } - if rule is true, execute action
{ (c) => c.ConnectionString == null , (c) => c.ConnectionString = "foo" },
{ (c) => c.OutputExcelFilePath == null, (c) => c.ConnectionString = "bar" },
{ (c) => c.OutputDirectory == null, (c) => c.OutputDirectory = "baz" }
};
//Nothing to select, but we want to loop throough the dict and invoke action, if rule is true.
//It is a pity there is no extension method called DoForEach on collections.
defaults.Select((item) => item.Key.Invoke(configuration) ? item.Value.Invoke(configuration) : default(void) );
}
我意识到我可以使用 if-else 语句而不是三元运算符(或者我可以调用一个虚拟方法来返回 void)。此外,Select 扩展方法不喜欢返回 void 的 lambda。似乎说无法推断类型,但当然如果我这样指定类型,要么:
defaults.Select<ApplicationConfiguration, void>((item) => { if (item.Key.Invoke(configuration)) item.Value.Invoke(configuration); } );
从语言设计的角度来看,我很好奇,为什么我们没有可以返回 void 的表达式或 void 变量的数据类型。