函数接受KeyValuePair的通用IEnumerable

时间:2014-02-12 20:52:47

标签: c# generics

我正在尝试编写一个扩展方法,这对于快速查看IEnumerable<KeyValuePair<object, object>>的内容非常有用。我正好在编写签名时遇到一些麻烦。下面的代码适用于字符串,但我希望能够在任何通用类型的KeyValuePair上使用它。如果将其更改为接受IEnumerable<KeyValuePair<object, object>>,则尝试在Dictionary<string,string>类型上调用它我收到编译器错误“实例参数:无法从'System.Collections.Generic.Dictionary'转换为'System.Collections。 Generic.IEnumerable&gt;'“即使Dictionary<TKey, TValue>实现了接口IEnumerable<KeyValuePair<TKey, TValue>>

public static string ToHumanReadableString(this IEnumerable<KeyValuePair<string, string>> dictionary)
{
  if (dictionary.IsNull())
  {
    return "{null}";
  }
  StringBuilder sb = new StringBuilder();
  foreach (KeyValuePair<string, string> kvp in dictionary)
  {
    if (!kvp.Value.IsNull())
    {
      sb.AppendLineAndFormat("{0}={1}", kvp.Key.ToString(), kvp.Value.ToString());
    }
    else
    {
      sb.AppendLineAndFormat("{0}={null}", kvp.Key.ToString());
    }
  }
  return sb.ToString();
}

2 个答案:

答案 0 :(得分:4)

您可以使方法通用(注意注释中的更改):

public static string ToHumanReadableString<TKey, TValue>(
    this IEnumerable<KeyValuePair<TKey, TValue>> dictionary)
{
    if (dictionary == null)
    {
        return "{null}";
    }
    StringBuilder sb = new StringBuilder();
    foreach (var kvp in dictionary)  // note change
    {
        if (kvp.Value == null)   // note change
        {
            sb.AppendLineAndFormat("{0}={1}", kvp.Key.ToString(), kvp.Value.ToString());
        }
        else
        {
            sb.AppendLineAndFormat("{0}={null}", kvp.Key.ToString());
        }
    }
    return sb.ToString();
}

请注意,我还将括号格式化为使用更多标准缩进。

答案 1 :(得分:2)

使函数通用,如下所示:

public static string ToHumanReadableString<TKey, TValue>(
    this IEnumerable<KeyValuePair<TKey, TValue>> dictionary)
    where TKey : class
    where TValue : class
{
    if (dictionary.IsNull())
    {
        return "{null}";
    }
    StringBuilder sb = new StringBuilder();
    foreach (var kvp in dictionary)
    {
        if (!kvp.Value.IsNull())
        {
            sb.AppendLineAndFormat("{0}={1}", kvp.Key.ToString(), kvp.Value.ToString());
        }
        else
        {
            sb.AppendLineAndFormat("{0}={null}", kvp.Key.ToString());
        }
    }
    return sb.ToString();
}

请注意,我还添加了constraintsTKeyTValue类型必须是类,否则您的空检查没有多大意义。