我有这样的代码使其更好(modbus_master.SetValue("x1",Convert.ToInt32(resipeDosings [i] .Massa)*10,1); - 向控制器发送数据)
public class RecipeDosings
{
public string Product { get; set; }
public string Persent { get; set; }
public string Massa { get; set; }
public string Bunker { get; set; }
public RecipeDosings(string product, string persent, string massa, string bunker)
{
this.Product = product;
this.Persent = persent;
this.Massa = massa;
this.Bunker = bunker;
}
}
public List<RecipeDosings> resipeDosings = new List<RecipeDosings>();
for (int i = 0; i < resipeDosings.Count; i++)
{
if (resipeDosings[i].Bunker == "Bunker 1")
{
modbus_master.SetValue("x1", Convert.ToInt32(resipeDosings[i].Massa) * 10, 1);
}
if (resipeDosings[i].Bunker == "Bunker 2")
{
modbus_master.SetValue("x1", Convert.ToInt32(resipeDosings[i].Massa) * 10, 1);
}
if (resipeDosings[i].Bunker == "Bunker 3")
{
modbus_master.SetValue("x1", Convert.ToInt32(resipeDosings[i].Massa) * 10, 1);
}
if (resipeDosings[i].Bunker == "Bunker 4")
{
modbus_master.SetValue("x1", Convert.ToInt32(resipeDosings[i].Massa) * 10, 1);
}
if (resipeDosings[i].Bunker == "Bunker 5")
{
modbus_master.SetValue("x1", Convert.ToInt32(resipeDosings[i].Massa) * 10, 1);
}
if (resipeDosings[i].Bunker == "Bunker 6")
{
modbus_master.SetValue("x1", Convert.ToInt32(resipeDosings[i].Massa) * 10, 1);
}
if (resipeDosings[i].Bunker == "Bunker 7")
{
modbus_master.SetValue("x1", Convert.ToInt32(resipeDosings[i].Massa) * 10, 1);
}
if (resipeDosings[i].Bunker == "Bunker 8")
{
modbus_master.SetValue("x1", Convert.ToInt32(resipeDosings[i].Massa) * 10, 1);
}
if (resipeDosings[i].Bunker == "Bunker 9")
{
modbus_master.SetValue("x1", Convert.ToInt32(resipeDosings[i].Massa) * 10, 1);
}
}
Run Code Online (Sandbox Code Playgroud)
Switch语句删除所有if语句 -
switch (resipeDosings[i].Bunker)
{
case "Bunker 1":
// code here
break;
case "Bunker 2":
// code here
break;
// repeat case statements...
default:
// this is the final 'else' code - if nothing matches
}
Run Code Online (Sandbox Code Playgroud)
但是,有两件事是显而易见的:
构建LUT的最简单方法是使用a Dictionary<>.
Dictionary<string, int> bunkerLut = new Dictionary<string, int>();
bunkerLut["Bunker 1"] = 10;
bunkerLut["Bunker 2"] = 11;
bunkerLut["Bunker 3"] = 12;
// and so on... I'm assuming there should be a value that's different for each bunker? I'm also assuming it's an int
Run Code Online (Sandbox Code Playgroud)
然后你可以查找,就像这样(假设10是值的变化):
int result = bunkerLut[resipeDosings[i].Bunker];
modbus_master.SetValue("x1", Convert.ToInt32(resipeDosings[i].Massa) * result, 1);
Run Code Online (Sandbox Code Playgroud)
其他选项是将值存储在配置文件或数据库中.
| 归档时间: |
|
| 查看次数: |
148 次 |
| 最近记录: |