首页 > 解决方案 > 静态或非静态更适合在字符串生成器上添加变量?

问题描述

原谅我是 C# 的新手。我需要创建一个类,它将用值填充字符串生成器。所以我可以用两种方法做到这一点。

 public class QrCode
 {

     private static StringBuilder str=new StringBuilder();
     public static void PopulateString(int value1,int value2,decimal value3)
     {
         str.Append(value1 + "|" + value2 + "|" + value3 + "|");
     } 

     public static void Init()
     {
         str.Clear();
     }

     public static string GetResult()
     {
         return str.ToString();
     }

 }

同样在我的表格中,我正在使用它。

QrCode.Init();  
for(int a = 0; i<=grid.RowsCount; i++)
QrCode.PopulateString(
  Convert.ToInt32(grid.GetFocusedRowCellValue("value1")),
  Convert.ToInt32(grid.GetFocusedRowCellValue("value2")),
  Convert.ToDecimal(grid.GetFocusedRowCellValue("value3"))
);
var result=QrCode.GetResult();
//rest of my code

第二种方法是使用非静态字段示例:

public class QrCode
 {

     private StringBuilder str=new StringBuilder();
     public void PopulateString(int value1,int value2,decimal value3)
     {
         str.Append(value1 + "," + value2 + "," + value3 + ",");
     } 
 }

在我的表格里面:

 var qrCode = new QrCode();
 for(int a=0; i<=grid.RowsCount; i++)
   qrCode.PopulateString(
    Convert.ToInt32(grid.GetFocusedRowCellValue("value1")),
    Convert.ToInt32(grid.GetFocusedRowCellValue("value2")),
    Convert.ToDecimal(grid.GetFocusedRowCellValue("value3"))
  );
  var result=qrCode.GetResult();
   //rest of my code

所以我的问题是,哪两个是更好的做法?还有哪个性能更好,哪个内存更少。这两种方法都非常有效!我只是在寻找最好的方法。

标签: c#

解决方案


扩展我上面的评论:如果以下应该有效,那么 static 不是一个选项:

void doSomething()    
{
   QRCode code1 = new QRCode();
   QRCode code2 = new QRCode();

   code1.Populate("1,2,3");
   code2.Populate("4,5,6");

  // the content with the static implementation would now contain data from BOTH Populate calls - since the StringBuilder is 'shared' amongst instances.
}

推荐阅读