我有这个方法,这按预期工作,如果字符串为空,它不插入<string, value>
,但是我有一个问题,字符串不总是存在。如果字符串不存在,我想避免附加任何内容。
public static class StringBuilderExtension
{
public static void AppendIfNotNull<TValue>(this StringBuilder sb, TValue value, string prefix)
where TValue : class
{
if (value != null)
{
sb.Append(prefix + value);
}
}
}
问题是我总是传递字符串键
sb.AppendIfNotNull(" width=\"", component.style.width + "\"");
这将显示为width=""
,因为我实际上附加了字符串。我怎么能阻止这种情况发生。
如果我将它包装在if语句中,我可以阻止它出现
if (item.width!= null)
{
sb.AppendIfNotNull(" width=\"", item.width + "\"");
}
对象示例。属性可能存在于一个对象中,但可能不存在于下一个对象中例如如果颜色不存在,请不要追加颜色:
{
'id': 'Test',
'type': 'Text',
'style': {
'color': 'black'
'textSize': '12'
}
},
{
'id': 'Test',
'type': 'Text',
'style': {
'textSize': '12'
}
}
你可以简单地将你的添加从string prefix
更改为接受TValue
的函数并返回string
public static class StringBuilderExtension
{
public static void AppendIfNotNull<TValue>(this StringBuilder sb, TValue value, Func<TValue, string> transform)
where TValue : class
{
if (value != null)
{
sb.Append( transform( value ));
}
}
}
在这种情况下,只有在实际拥有有效值时才会调用转换
使用它的一种示例方式可能是
sb.AppendIfNotNull( token.style?.width, value => $" width=\"{value}\"" );
?
意味着条件空检查(所以如果token.style
为null,它也将为null)
我在dotnetfiddle中添加了一个小样本,在那里我删除了泛型类型限制(因为我在输入数字;))
使用当前方法签名无法做到这一点,但您可以单独传递前缀,值和后缀:
public static void AppendIfNotNull<TValue>(this StringBuilder sb, TValue value, string prefix, string suffix)
where TValue : class
{
if (value != null)
{
sb.Append(prefix + value + suffix);
}
}
sb.AppendIfNotNull(item.width, " width=\"", "\"");