【发布时间】:2021-05-02 15:31:41
【问题描述】:
我想创建一个静态Dictionary,它将值映射到委托。使用 Add 时,效果很好:
class MyClass {
private delegate void _processStatement(Statement statement);
private static Dictionary<Statement.Types, _processStatement> _statementProcessors =
new Dictionary<Statement.Types, _processStatement>();
public MyClass() {
_statementProcessors.Add(Statement.Types.Increment, Increment);
}
private void Increment(Statement s) {}
}
但是,我想在实例化时初始化它们,如下所示:
class MyClass {
private delegate void _processStatement(Statement statement);
private static Dictionary<Statement.Types, _processStatement> _statementProcessors =
new Dictionary<Statement.Types, _processStatement>() {
{ Statement.Types.Increment, Increment }
}
}
private void Increment(Statement s) {}
}
这给了我错误
集合初始值设定项的最佳重载 Add 方法 'Dictionary
.Add(Statement.Types, Machine._processStatement)' 有一些无效参数
我不完全理解。
有没有可能,我想要实现的目标是什么?还是我必须在构造函数中初始化它?
更新在构造函数中添加它时出现此运行时错误:
已添加具有相同密钥的项目。键:增量
【问题讨论】:
-
Statement.Types.Increment 是如何成为私有委托 _processStatement 的委托的?
-
Statement.Types.Increment是键,代理Increment()是值,在字典中。 -
字典初始化符号
new Dictionary<, >() { [Statement.Types.Increment] = Increment }工作吗?如果不是,您可能需要使用强制转换,即(_processStatement)Increment或可能是 lambda 表示法(Statement x) => Increment(x),并查看 IDE 是否建议进行代码修复以使其更简洁 -
不,我的意思是,您是否尝试过我建议的特定语法。有两种类型的集合初始化器可用于字典。一个像你用的,另一个像我建议的(仔细看,方括号)
-
@pinkfloydx33 是的,我明白了,这就是我删除评论的原因。当我尝试这样做时,我收到错误
A field initializer cannot reference the non-static field, method, or property 'Machine.Increment(Statement)'
标签: c# dictionary delegates