CA1800:不要投不必要

,同时实施的一段代码我得到下面的错误CA1800:不要投不必要

“的参数,被铸造在方法类型‘列表框’多次高速缓存中的‘作为’操作的结果,或者直接投射以消除冗余投影类指令。“

代码:

private static void LibrarayMethod(object sender) 

{

try

{

if (((ListBox)(sender)).SelectedItems.Count > 0)

{

MainView.GetInstance.Library.SelectedBook = ((ListBox)(sender)).SelectedItems[0].ToString();

}

}

catch (Exception ex)

{

Logger.Error("Error in Class - LibrarayMethod() method as ", ex);

}

}

请帮助解决这个错误。

回答:

的信息是很清楚的:不是众多蒙上(ListBox)(sender)把刚刚一个sender as ListBox

private static void LibrarayMethod(object sender) { 

ListBox box = sender as ListBox;

// sender is ListBox and the listbox has selected items

if (box != null && box.SelectedItems.Count > 0)

MainView.GetInstance.Library.SelectedBook = box.SelectedItems[0].ToString();

}

甚至(短,但是,可能的可读性):

private static void LibrarayMethod(object sender) { 

ListBox box = sender as ListBox;

if (box?.SelectedItems.Count > 0)

box.SelectedItems[0].ToString();

}

回答:

var listbox = (ListBox)sender; 

if (listbox.SelectedItems.Count > 0)

{

MainView.GetInstance.Library.SelectedBook = listbox.SelectedItems[0].ToString();

}

以上是 CA1800:不要投不必要 的全部内容, 来源链接: utcz.com/qa/262468.html

回到顶部