我有像
这样的大字符串列表实际上我正在使用二进制Writer
case btn_click:
BinaryWriter bw = new BinaryWriter(File.OpenWrite(theFiles));
for (int i = 0x000004; i <= 0x000005; i++)
{
bw.BaseStream.Position = 0x000004;
string cmp = spn1.SelectedItem.ToString();
if (cmp == "A") bw.Write(0x0123);
if (cmp == "B") bw.Write(0x0456);
if (cmp == "C") bw.Write(0x0789);
}
for (int i = 0x000008; i <= 0x000009; i++)
{
bw.BaseStream.Position = 0x000008;
string cmp = spn2.SelectedItem.ToString();
if (cmp == "A") bw.Write(0x0123);
if (cmp == "B") bw.Write(0x0456);
if (cmp == "C") bw.Write(0x0789);
}
for (int i ...
{
...
}
...
如何避免重写字符串a,b,c?
所以@Olexiy Dymashok的回答我可以解决问题^^ 我把字符串cmp放在公共场所
public string cmp { get; private set; }
for (int i = 0x000004; i <= 0x000005; i++)
{
bw.BaseStream.Position = 0x000004;
cmp = spn1.SelectedItem.ToString();
bw.Write(SelectDataForBinaryWriter("ListData"));
}
for (int i = 0x000004; i <= 0x000005; i++)
{
bw.BaseStream.Position = 0x000004;
cmp = spn2.SelectedItem.ToString();
bw.Write(SelectDataForBinaryWriter("ListData"));
}
private int SelectDataForBinaryWriter(string input)
{
int output = 0;
if (cmp == "A") output = 0x0000;
if (cmp == "B") output = 0x0123;
if (cmp == "C") output = 0x0456;
return output;
}
谢谢你
答案 0 :(得分:0)
您可以创建一个包含a,b和c作为常量字段的静态类。
public static class Arbitrary
{
public const string A = "test";
...
}
答案 1 :(得分:0)
如果这些字符串对于所有情况都相同 - 将它们设为全局:
string a = "test";
string b = "try";
string c = "compare";
//case 1
for (int i = 1; i <= 2; i++)
{
if (a == b) { do something };
if (a == c) { do something};
}
//case 2
for (int i = 3; i <= 4; i++)
{
if (a == b) { do something };
if (a == c) { do something};
}
这样做可以避免在每种情况下重复初始化此字符串
修改1
您可以创建选择值的功能:
for (int i = 1; i <= 2; i++)
{
bw.Write(SelectDataForBinaryWriter("A"));
}
...
private int SelectDataForBinaryWriter(string input)
{
int output = 0;
switch (input) // edit your own cases here
{
case "A":
output = 0x123;
break;
case "B":
output = 0x456;
break;
case "C":
output = 0x789;
break;
default:
output = some_default_value_here;
break;
}
return output;
}
正如我所看到的,您正在编写十六进制值,因此您也可以考虑返回已经解析的值 - C# convert integer to hex and back again