问题
I have created an IDictionary
extension to write IDictionary Exception.Data
values to a string.
The extension code:
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));
}
}
When I use this extension on Exception.Data.ToString("=", "|")
I get error
The type arguments cannot be inferred from the usage.
Any idea how to solve this?
回答1:
Exception.Data is of type IDictionary
, not IDictionary<TKey, TValue>
.
You need to change your extension method to this:
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));
}
回答2:
The exception is pointing that you are missing a cast.
I copied your code in a test project but I was unable to reproduce your error.
Try using x.Key.ToString()
and x.Value.ToString()
.
The only thing I found is an error raised when Dictionary is empty:
sb.ToString(0, sb.Length - 1)
when lenght is zero is not working
来源:https://stackoverflow.com/questions/12197089/idictionary-to-string