在Delphi中,如何填充TDictionary示例代码中的内容?
- 内容介绍
- 相关推荐
本文共计363个文字,预计阅读时间需要2分钟。
csharp// 示例代码,创建一个TDictionary实例并填充TDictionary dictionary=new TDictionary(s);
// 假设有一个TEnumerable
// 使用dictionary的Add方法填充字典foreach (var pair in collection){ dictionary.Add(pair.Key, pair.Value);}
有没有人有TDictionary< TKey,TValue>的示例代码?在构造函数中填充? 您需要调用接收类型为TEnumerable< TPair< TKey,TValue>>类型的Collection参数的 dictionary constructor overload.例如,假设我们有TDictionary< string,Integer>.然后我们可以向构造函数传递一个TEnumerable< TPair< string,Integer>>的实例.这种事的一个例子是TList<TPair<string, Integer>>.
List := TList<TPair<string, Integer>>.Create; List.Add(TPair<string, Integer>.Create('Foo', 42)); List.Add(TPair<string, Integer>.Create('Bar', 666)); Dictionary := TDictionary<string, Integer>.Create(List);
这是非常笨拙的,你永远不会喜欢这个选项而不是简单的Create,然后是一系列对Add的调用.如果你碰巧手边有一个现成的集合,你只能使用传入现有集合的选项.
从TEnumerable< T>派生的类的另一个例子.是TDictionary本身:
type TDictionary<TKey,TValue> = class(TEnumerable<TPair<TKey,TValue>>)
因此,如果您已经有一个字典实例,则可以创建另一个实例并使用第一个实例的内容对其进行初始化:
Dict2 := TDictionary<string, Integer>.Create(Dict1);
本文共计363个文字,预计阅读时间需要2分钟。
csharp// 示例代码,创建一个TDictionary实例并填充TDictionary dictionary=new TDictionary(s);
// 假设有一个TEnumerable
// 使用dictionary的Add方法填充字典foreach (var pair in collection){ dictionary.Add(pair.Key, pair.Value);}
有没有人有TDictionary< TKey,TValue>的示例代码?在构造函数中填充? 您需要调用接收类型为TEnumerable< TPair< TKey,TValue>>类型的Collection参数的 dictionary constructor overload.例如,假设我们有TDictionary< string,Integer>.然后我们可以向构造函数传递一个TEnumerable< TPair< string,Integer>>的实例.这种事的一个例子是TList<TPair<string, Integer>>.
List := TList<TPair<string, Integer>>.Create; List.Add(TPair<string, Integer>.Create('Foo', 42)); List.Add(TPair<string, Integer>.Create('Bar', 666)); Dictionary := TDictionary<string, Integer>.Create(List);
这是非常笨拙的,你永远不会喜欢这个选项而不是简单的Create,然后是一系列对Add的调用.如果你碰巧手边有一个现成的集合,你只能使用传入现有集合的选项.
从TEnumerable< T>派生的类的另一个例子.是TDictionary本身:
type TDictionary<TKey,TValue> = class(TEnumerable<TPair<TKey,TValue>>)
因此,如果您已经有一个字典实例,则可以创建另一个实例并使用第一个实例的内容对其进行初始化:
Dict2 := TDictionary<string, Integer>.Create(Dict1);

