\编辑sb.Append中的代码获取异常("允许前缀:")行 \类型' System.ArgumentNullException'发生在System.Core.dll中但未在用户代码中处理
public partial class IndexingPolicy:IEquatable
{
public IndexingPolicy(List<string> allowPrefixes = default(List<string>), List<string> denyPrefixes = default(List<string>), bool? disableIndexing = default(bool?))
{
this.AllowPrefixes = allowPrefixes;
this.DenyPrefixes = denyPrefixes;
this.DisableIndexing = disableIndexing;
}
[DataMember(Name="allowPrefixes", EmitDefaultValue=false)]
public List<string> AllowPrefixes { get; set; }
[DataMember(Name="denyPrefixes", EmitDefaultValue=false)]
public List<string> DenyPrefixes { get; set; }
[DataMember(Name="disableIndexing", EmitDefaultValue=false)]
public bool? DisableIndexing { get; set; }
").Append(DisableIndexing).Append("\n");
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class IndexingPolicy {\n");
sb.Append(" AllowPrefixes: ").Append(
string.Join(",", AllowPrefixes.ToList())
).Append("\n");
sb.Append(" DenyPrefixes: ").Append(
string.Join(",", DenyPrefixes.ToList())
).Append("\n");
sb.Append(" DisableIndexing: ").Append(DisableIndexing).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
答案 0 :(得分:1)
问题是默认的ToString()函数只描述了类(在本例中为png
1 [System.String]`)。要获取字符串,您必须以某种方式覆盖字符串,或将列表内容转换为您要查找的字符串。
我喜欢在这种情况下使用string.Join()。
System.Collections.Generic.List
...作为一个旁注,我发现使用带有string.Join的数组比使用stringbuilder更“干净”,但效果也不错。
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class IndexingPolicy {\n");
sb.Append(" AllowPrefixes: ").Append(
string.Join(",", AllowPrefixes.ToList())
).Append("\n");
sb.Append(" DenyPrefixes: ").Append(
string.Join(",", DenyPrefixes.ToList())
).Append("\n");
sb.Append(" DisableIndexing: ").Append(
string.Join(","< DisableIndexing.ToList())
).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
...如果使用加法使用扩展方法:
public override string ToString()
{
var response = new List<string>() {
"class IndexingPolicy {",
$" AllowPrefixes: {string.Join(",", AllowPrefixes.ToList())}",
$" DenyPrefixes: {string.Join(",", DenyPrefixes.ToList())}",
$" DisableIndexing: {string.Join(",", DisableIndexing.ToList())}",
"}",
""
return string.Join(Environment.NewLine, response);
}
它变得更漂亮:
public static string Join(this IEnumerable @this, string connector)
=> string.Join(connector, @this.ToList());