使用扩展名仅在StringBuilder中附加现有字符串/值

问题描述 投票:0回答:2

我有这个方法,这按预期工作,如果字符串为空,它不插入<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'
    }
}
c# stringbuilder
2个回答
2
投票

你可以简单地将你的添加从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中添加了一个小样本,在那里我删除了泛型类型限制(因为我在输入数字;))


0
投票

使用当前方法签名无法做到这一点,但您可以单独传递前缀,值和后缀:

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=\"", "\"");
© www.soinside.com 2019 - 2024. All rights reserved.