C#中扩展StringBuilder支持链式方法

 

本篇体验扩展StringBuilder使之支持链式方法。

这里有一个根据键值集合生成select元素的方法。

 

private static string BuilderSelectBox(IDictionary<int, string> options, string id, bool includeUnknown)
{
    var html = new StringBuilder();
    html.AppendFormat("<select id=\"{0}\" name=\"{0}\">", id);
    html.AppendLine();
    
    if(includeUnknown)
    {
        html.AppendLine("\t<option>Unknown</option>");
    }
    
    foreach(var opt in options)
    {
        html.AppendFormat("\t<option value=\"{0}\">{1}</option>", opt.Key, opt.Value);
        html.AppendLine();
    }
    
    html.AppendLine("</select>");
    
    return html.ToString();
}

 

以上,

html.AppendFormat("<select id=\"{0}\" name=\"{0}\">", id);
html.AppendLine();

可以对这两个语句封装,扩展StringBuilder。
            
            
改成

public static class StringBuilderExtensions
{
    public static StringBuilder AppendFormattedLine(this StringBuilder @this, string format, prams object[] args) => @this.AppendFormat(format, args).AppendLine();
}

private static string BuilderSelectBox(IDictionary<int, string> options, string id, bool includeUnknown)
{
    var html = new StringBuilder()
        .AppendFormattedLine("<select id=\"{0}\" name=\"{0}\">", id);

    
    if(includeUnknown)
    {
        html.AppendLine("\t<option>Unknown</option>");
    }
    
    foreach(var opt in options)
    {
        html.AppendFormattedLine("\t<option value=\"{0}\">{1}</option>", opt.Key, opt.Value);
        html.AppendLine();
    }
    
    html.AppendLine("</select>");
    
    return html.ToString();
}

 

以上,

    if(includeUnknown)
    {
        html.AppendLine("\t<option>Unknown</option>");
    }

可以对如上语句进行封装,继续扩展StringBuilder.

 

public static class StringBuilderExtensions
{
    public static StringBuilder AppendFormattedLine(this StringBuilder @this, string format, prams object[] args) => @this.AppendFormat(format, args).AppendLine();
    
    public static StringBuilder AppendLineWhen(this StringBuilder @this, Func<bool> predicate, string value) =>
    predicate() 
        ? @this.AppendLine(value)
        : @this;
    
}

private static string BuilderSelectBox(IDictionary<int, string> options, string id, bool includeUnknown)
{
    var html = new StringBuilder()
        .AppendFormattedLine("<select id=\"{0}\" name=\"{0}\">", id)
        .AppendLineWhen(() => includeUnknown, "\t<option>Unknown</option>");

    
    foreach(var opt in options)
    {
        html.AppendFormattedLine("\t<option value=\"{0}\">{1}</option>", opt.Key, opt.Value);
    }
    
    html.AppendLine("</select>");
    
    return html.ToString();
}

 

 

public static class StringBuilderExtensions
{
    public static StringBuilder AppendFormattedLine(this StringBuilder @this, string format, prams object[] args) => @this.AppendFormat(format, args).AppendLine();
    
    public static StringBuilder AppendLineWhen(this StringBuilder @this, Func<bool> predicate, string value) =>
    predicate() 
        ? @this.AppendLine(value)
        : @this;
        
    public static StringBuilder AppendWhen(this StringBuilder @this, Func<bool> predicate, Func<StringBuilder, StringBuilder> fn) =>
    predicate()
        ? fn(@this)
        : @this;
    
}

private static string BuilderSelectBox(IDictionary<int, string> options, string id, bool includeUnknown)
{
    var html = new StringBuilder()
        .AppendFormattedLine("<select id=\"{0}\" name=\"{0}\">", id)
        .AppendWhen(
            () => includeUnknown,
            sb => sb.AppendLine("\t<option>Unknown</option>")
        );

    
    foreach(var opt in options)
    {
        html.AppendFormattedLine("\t<option value=\"{0}\">{1}</option>", opt.Key, opt.Value);
    }
    
    html.AppendLine("</select>");
    
    return html.ToString();
}

 

以上,

    foreach(var opt in options)
    {
        html.AppendFormattedLine("\t<option value=\"{0}\">{1}</option>", opt.Key, opt.Value);
    }
    
对遍历语句进行封装,扩展StringBuilder,最终:   

 

public static class StringBuilderExtensions
{
    public static StringBuilder AppendFormattedLine(this StringBuilder @this, string format, prams object[] args) => @this.AppendFormat(format, args).AppendLine();
    
    public static StringBuilder AppendLineWhen(this StringBuilder @this, Func<bool> predicate, string value) =>
    predicate() 
        ? @this.AppendLine(value)
        : @this;
        
    public static StringBuilder AppendWhen(this StringBuilder @this, Func<bool> predicate, Func<StringBuilder, StringBuilder> fn) =>
    predicate()
        ? fn(@this)
        : @this;
        
    public static StringBuilder AppendSequence<T>(this StringBuilder @this, IEnumerable<T> seq, Func<StringBuilder, T, StringBuilder> fn) => seq.Aggregate(@this, fn);
    
}

private static string BuilderSelectBox(IDictionary<int, string> options, string id, bool includeUnknown)
{
    var html = new StringBuilder()
        .AppendFormattedLine("<select id=\"{0}\" name=\"{0}\">", id)
        .AppendWhen(
            () => includeUnknown,
            sb => sb.AppendLine("\t<option>Unknown</option>")
        )
        .AppendSequence(options, (sb, opt) => sb.AppendFormattedLine("\t<option value=\"{0}\">{1}</option>", opt.Key, opt.Value))
        .AppendLine("</select>")
        .ToString();
}

 

转载于:https://www.cnblogs.com/darrenji/p/5271696.html

C#StringBuilder是一个用于创建和修改字符串的可变字符序列类。它提供了一种灵活的方式来处理字符串的追加、插入、删除和替换等操作。在C语言,由于没有直接等价的类或结构体,我们需要手动实现一个类似的动态字符串操作功能。 以下是一个简化版的C语言实现,用于模拟StringBuilder的功能: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define INITIAL_CAPACITY 16 #define GROW_FACTOR 2 typedef struct { char *buffer; int length; int capacity; } StringBuilder; StringBuilder *StringBuilder_Create() { StringBuilder *sb = (StringBuilder *)malloc(sizeof(StringBuilder)); sb->buffer = (char *)malloc(INITIAL_CAPACITY * sizeof(char)); sb->length = 0; sb->capacity = INITIAL_CAPACITY; sb->buffer[0] = '\0'; return sb; } void StringBuilder_Destroy(StringBuilder *sb) { if (sb) { free(sb->buffer); free(sb); } } void StringBuilder_Append(StringBuilder *sb, const char *value) { if (!sb) return; int valueLength = strlen(value); while (sb->length + valueLength >= sb->capacity) { sb->capacity *= GROW_FACTOR; sb->buffer = (char *)realloc(sb->buffer, sb->capacity); } memcpy(sb->buffer + sb->length, value, valueLength); sb->length += valueLength; sb->buffer[sb->length] = '\0'; } void StringBuilder_Clear(StringBuilder *sb) { if (sb) { sb->length = 0; sb->buffer[0] = '\0'; } } const char *StringBuilder_ToString(StringBuilder *sb) { if (!sb) return NULL; return sb->buffer; } int main() { StringBuilder *sb = StringBuilder_Create(); StringBuilder_Append(sb, "Hello, "); StringBuilder_Append(sb, "World!"); printf("%s\n", StringBuilder_ToString(sb)); StringBuilder_Destroy(sb); return 0; } ``` 这段代码创建了一个简单的StringBuilder结构体和相关函数。其`StringBuilder_Create`函数用于初始化StringBuilder对象,`StringBuilder_Destroy`用于销毁对象释放内存,`StringBuilder_Append`用于追加字符串,`StringBuilder_Clear`用于清空StringBuilder内容,最后`StringBuilder_ToString`用于获取最终构建的字符串。 注意,这里的实现是一个简化的版本,它没有处理所有可能的边界情况,也没有提供完整的StringBuilder功能,例如插入、删除等操作。在实际应用可能需要更复杂的错误处理和动态数组管理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值