gpt4 book ai didi

c# - IDictionary 到字符串

转载 作者:太空宇宙 更新时间:2023-11-03 18:38:11 24 4
gpt4 key购买 nike

我创建了一个 IDictionary 扩展来将 IDictionary Exception.Data 值写入字符串。

扩展代码:

public static class DictionaryExtension
{
public static string ToString<TKey, TValue>(this IDictionary<TKey, TValue> source, string keyValueSeparator, string sequenceSeparator)
{
if (source == null)
throw new ArgumentException("Parameter source can not be null.");

return source.Aggregate(new StringBuilder(), (sb, x) => sb.Append(x.Key + keyValueSeparator + x.Value + sequenceSeparator), sb => sb.ToString(0, sb.Length - 1));
}
}

当我在 Exception.Data.ToString("=", "|") 上使用此扩展时,出现错误

无法从用法中推断类型参数。

知道如何解决这个问题吗?

最佳答案

Exception.Data 类型为 IDictionary , 不是 IDictionary<TKey, TValue> .

您需要将扩展​​方法更改为:

public static string ToString(this IDictionary source, string keyValueSeparator,
string sequenceSeparator)
{
if (source == null)
throw new ArgumentException("Parameter source can not be null.");

return source.Cast<DictionaryEntry>()
.Aggregate(new StringBuilder(),
(sb, x) => sb.Append(x.Key + keyValueSeparator + x.Value
+ sequenceSeparator),
sb => sb.ToString(0, sb.Length - 1));
}

关于c# - IDictionary 到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12197089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com