我希望有一个字典,当找不到搜索键时返回默认值.阅读文档:
Generics.Collections.Tdictionary [...]此类提供映射[...]和初始内容.
1 - 怎么样?有没有办法做到这一点ala Python:{1:'one'; 2:'两个'}?
Generics.Collections.TDictionary.TryGetValue [...]如果给定的键在字典中并在Value中提供其值,则TryGetValue返回true.否则,它返回false,并将Value设置为Tvalue的默认值类型.
2 - 如何设置此默认值?我找不到构造函数(可能我只是在错误的地方搜索过.我期待类似"构造函数Create(DefaultValue:TValue);")
所以我正在尝试实现自己的(可能没有必要.见上文):
代码是(欢迎评论和建议!):
unit Util;
interface
uses
Generics.collections;
type
//
// Dictionary with default response
//
TDefaultDictonary<K, V> = class(TObjectDictionary<K, V>)
private
M_DefaultValue : V;
public
constructor Create(Defaultvalue : V);
destructor Destroy; reintroduce;
function GetDefaultValue : V;
function TryGetValue(const Key: K; out Value: V): Boolean;
function GetValueOf(const Key: K) : V;
end;
implementation
//
// Contructor and destructor
//
constructor TDefaultDictonary<K, V>.Create(Defaultvalue : V);
begin
inherited Create;
M_DefaultValue …Run Code Online (Sandbox Code Playgroud)