如何使用“?:”更短地缩短此代码 [英] How can I make this code shorter using "?:"
本文介绍了如何使用“?:”更短地缩短此代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对所有DGV列重复此代码。我认为定义很多变量会影响性能。通知我需要x变量,因为代码中的某处我用它们来计算。
this code is repeated for all columns of DGV. I think defining a lot of variables will affect performance.notice I need "x" variables because somewhere in code I use them for calculating.
TimeSpan x1 = TimeSpan.Zero;
string s1 = dataGridView1.Rows[i].Cells["MrnngEnt"].Value.ToString();
if (!string.IsNullOrEmpty(s1))
x1 = TimeSpan.Parse(s1= (s1 == "24:00:00") ? "23:59:59" : s1);
推荐答案
嗯,你可以得到所有
if (!string.IsNullOrEmpty(s1))
x1 = TimeSpan.Parse(s1= (s1 == "24:00:00") ? "23:59:59" : s1);
再次使用三元运算符作为单行。
as a single line using the ternary operator again.
x1 = (!string.IsNullOrEmpty(s1)) ? TimeSpan.Parse(s1 = (s1 == "24:00:00") ? "23:59:59" : s1) : TimeSpan.Zero
但我个人会写一个小帮手函数来为你做数据调整。例如。
But personally I would write a little helper function to do that data adjustment for you. E.g.
private TimeSpan AdjustTime(int row, string colName)
{
string s1 = dataGridView1.Rows[row].Cells[colName].Value.ToString();
return ((!string.IsNullOrEmpty(s1)) ? TimeSpan.Parse(s1 = (s1 == "24:00:00") ? "23:59:59" : s1) : TimeSpan.Zero);
}
然后你会像这样用它
Then you would use it like this
TimeSpan x1 = AdjustTime(i, "MrnngEnt");
TimeSpan x2 = AdjustTime(i, "NextColumn");
我认为进行这样的子优化(例如减少变量数量)没有意义,因为,因为,可能:
- 您不需要优化(您确定应用程序的这部分是瓶颈吗?)
- 性能不受变量数量的影响。
- 编译器比我们更聪明,可以更有效地优化这些代码
I think making such sub-optimizations (such reducing the number of variables) does not make sense, because, probably:
- You don't need to optimize (are you sure this part of your application is the bottleneck?)
- Performance is not affected by the 'number of variables'.
- The compiler is smarter than us and could optimize such code more effectively
这篇关于如何使用“?:”更短地缩短此代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文