在新类中创建字符串构建器

时间:2014-10-08 05:02:54

标签: c# winforms stringbuilder

我想在c#中的新类中创建一个字符串构建器,因为我有许多要替换的字符串(超过7,000个)。以相同的形式执行可能会出现加载问题所以我想创建一个新类,我可以编写字符串生成器代码,但无法执行。我试过下面的代码

class v
    {
        StringBuilder _sb = new StringBuilder();

        public v(StringBuilder sb)
        {
            sb.Replace("s", "A");
            sb.Replace("hi", "hello");
        }
    }

我的按钮代码:

StringBuilder _sb = new StringBuilder(c1Editor1.Text);
_sb.v(C1Editor.text);

3 个答案:

答案 0 :(得分:2)

class v
{
    StringBuilder _sb;

    public v(StringBuilder sb)
    {
        _sb = sb;
        sb.Replace("s", "A");
        sb.Replace("hi", "hello");
    }
}

然后:

StringBuilder _sb = new StringBuilder(c1Editor1.Text);
v _v = new v(_sb);

并不是说我必须认为这是一个很好的代码,但这会实现你想要做的事情。

答案 1 :(得分:1)

如果你想改变你自己的stringbuiler文本,那么这个怎么样?

1.Create StringBuilder Handler

public static class StringHelper
{
    public static void v(this StringBuilder  sb)
    {
        sb.Replace("s", "A");
        sb.Replace("hi", "hello");
    }
}

2.代码中的用户处理程序类

StringBuilder sb = new StringBuilder(c1Editor1.Text);
sb.v();

答案 2 :(得分:0)

这是你如何做到的。将代码粘贴到一个表单中,其中TextBox名为textBox1Button名为button1BackgroundWorker名为backgroundWorker1

private void button1_Click(object sender, EventArgs e)
{
    // instead of changing the cursor you could disable the textbox
    this.UseWaitCursor = true;
    backgroundWorker1.DoWork += Replacer;
    backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
    backgroundWorker1.RunWorkerAsync(textBox1.Text);
}

private void Replacer(object sender, DoWorkEventArgs doWorkEventArgs)
{
    var replacer = new StringBuilder((String)doWorkEventArgs.Argument);
    replacer.Replace("s", "A");
    replacer.Replace("hi", "hello");
    // add other 6998 replacements here and remove the sleep of course
    Thread.Sleep(5000);
    doWorkEventArgs.Result = replacer.ToString();
}

void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    textBox1.Text = (string) e.Result;
    // instead of changing the cursor you could enable the textbox here
    this.UseWaitCursor = false;
}
祝你好运。

相关问题