创建一个派生自字符串构建器的类,以附加任意数量的字符串 [英] Create a class that derives from string builder to append any number of strings

查看:53
本文介绍了创建一个派生自字符串构建器的类,以附加任意数量的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个派生自字符串构建器的类,以附加任意数量的字符串。

我的程序应允许用户输入自己的字符串数量

示例用法:







i want to create a class that derives from string builder to append any number of strings.
My Program shoul allow the user input their own number of strings
example usage:



//Format Post Data

                StringBuilder postData = new StringBuilder();
                postData.Append("dst");
                postData.Append("&popup=true");
                postData.Append(String.Format("&username={0}", USERNAME_Validate1));// reads username from username textbox
                postData.Append(String.Format("&password={0}", PASSWORD_Validate1));// reads password from password textbox

                //Write Post Data To Server

                using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                    writer.Write(postData);





我尝试了什么:



i能够在代码中附加带字符串构建器的字符串,但我希望用户能够指定自己的字符串。



What I have tried:

i am able to append string with string builder inside the code but i want the user to be able to specify their own.

推荐答案

你不能。

你不能从StringBuilder派生,它是一个密封的类: MSDN StringBuilder [ ^ ]

你必须封装它:创建一个包含内部私有StringBuilder的新类,并公开所有必要的方法你自己。
You can't.
You cannot derive from StringBuilder, it is a sealed class: MSDN StringBuilder[^]
You will have to encapsulate it: create a new class which contains an internal private StringBuilder, and expose all the necessary methods yourself.


除了完全有效的解决方案1之外,你还可以在StringBuilder类上创建扩展方法。

类似于:

In addition to the perfectly valid Solution 1, you also have the ability to create extension methods on the StringBuilder class.
Something like:
public static class Utility
{
   public static StringBuilder AppendAnyNumberOfStrings(this StringBuilder sb, params string elements) {
      foreach (string element in elements) {
         sb.Append(element);
      }
      return sb;
   }
}



并且StringBuilder类已经有一个 AppendFormat 方法删除了需要在附加中使用 String.Format 方法。

StringBuilder.AppendFormat方法 [ ^ ]



希望这会有所帮助。


And the StringBuilder class already has an AppendFormat method which removes the need to use the String.Format method inside the Append one.
StringBuilder.AppendFormat method[^]

Hope this helps.


这篇关于创建一个派生自字符串构建器的类,以附加任意数量的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆