c# - 静态或非静态更适合在字符串生成器上添加变量?
问题描述
原谅我是 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
所以我的问题是,哪两个是更好的做法?还有哪个性能更好,哪个内存更少。这两种方法都非常有效!我只是在寻找最好的方法。
解决方案
扩展我上面的评论:如果以下应该有效,那么 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.
}
推荐阅读
- python - 如何将变量从 python 发送和更新到 html(Flask)?
- javascript - 如何使用 data-bind 属性获取 dom 元素作为参数 - 在我的 javascript 代码中进行操作?
- python - Odoo 中是否有使用它以多种名称销售产品但在库存中相同的产品?
- java - 我不知道如何更改我的程序,以便我可以看到十个最大的文件
- javascript - 按从 MongoDB 返回的值合并两个对象数组
- javascript - ApexCharts 强制 100% 高度
- angular - 如何在 Angular 4+ 上测试输入的标签?
- android - 片段内的Recyclerview片段
- amazon-web-services - Terraform:从快照创建 AWS Lightsail 实例
- python - 如何将词典发送到文本到语音