虽然我正在构建一个类来管理在Android中显示AlertDialog
的繁琐且重复的过程,但我偶然发现了这一点:
我应该将var的结果存储到var中并使用它而不是进行相同的比较 n 次吗?
在我的情况下,我进行了两次相同的比较(比较将始终保持相同,因为在这些比较之间我并没有改变任何可能改变结果的内容)
这就是我所拥有的:
public static AlertDialog BuildDialog( Activity activity, String header, String body, View view, DialogButton negative, DialogButton positive, DialogButton neutral ) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( activity );
alertDialogBuilder.SetTitle( header );
alertDialogBuilder.SetMessage( body );
if( view != null ) {
alertDialogBuilder.SetView( view );
}
if( positive == null && negative == null && neutral == null ) {
alertDialogBuilder.SetNeutralButton( "OK", (EventHandler<DialogClickEventArgs>) null );
} else {
if( negative != null ) {
alertDialogBuilder.SetNegativeButton( negative.Text, negative.Action );
}
if( neutral != null ) {
alertDialogBuilder.SetNeutralButton( neutral.Text, neutral.Action );
}
if( positive != null ) {
alertDialogBuilder.SetPositiveButton( positive.Text, positive.Action );
}
}
return alertDialogBuilder.Create();
}
这就是我现在所拥有的:
public static AlertDialog BuildDialog( Activity activity, String header, String body, View view, DialogButton negative, DialogButton positive, DialogButton neutral ) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( activity );
alertDialogBuilder.SetTitle( header );
alertDialogBuilder.SetMessage( body );
Boolean
hasView = view != null,
hasNeutral = neutral != null,
hasPositive = positive != null,
hasNegative = negative != null;
if( hasView ) {
alertDialogBuilder.SetView( view );
}
if( !hasNeutral && !hasPositive && !hasNegative ) {
alertDialogBuilder.SetNeutralButton( "OK", (EventHandler<DialogClickEventArgs>) null );
} else {
if( hasNegative ) {
alertDialogBuilder.SetNegativeButton( negative.Text, negative.Action );
}
if( hasNeutral ) {
alertDialogBuilder.SetNeutralButton( neutral.Text, neutral.Action );
}
if( hasPositive ) {
alertDialogBuilder.SetPositiveButton( positive.Text, positive.Action );
}
}
return alertDialogBuilder.Create();
}
虽然在这种特定情况下不应该有明显的影响,哪一个确实表现得更好,哪一个确实更好?
答案 0 :(得分:0)
.NET中的空比较非常便宜,所以做这样的事情的唯一原因是可读性,而不是执行速度。这与复杂条件尤其相关,例如
bool nonNegative = hasPositive || hasNeutral;
...
if (nonNegative) ...
导致更紧凑的代码更容易阅读。