我的一个同事重构了这段代码:
private void btnGeneral_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)e.OriginalSource;
Type type = this.GetType();
Assembly assembly = type.Assembly;
string userControlFullName = String.Format("{0}.{1}", type.Namespace, button.Name);
UserControl userControl = (UserControl)assembly.CreateInstance(userControlFullName);
}
对于这段代码:
private void btnGeneral_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)e.OriginalSource;
Type type = this.GetType();
Assembly assembly = type.Assembly;
UserControl userControl = (UserControl)assembly.CreateInstance(String.Format("{0}.{1}", type.Namespace, button.Name));
}
有人说如果一个变量只使用一次,就不需要创建变量。
我的回答是,创建仅使用一次的变量是好的做法,因为:
- 它作为注释并减少了注释(“userControlFullName”是清晰的)
- 使代码更容易阅读,即更多的代码“像英语一样阅读”
- 通过使用清晰的变量名称替换其中的部分,避免了过长的语句
- 更容易调试,因为您可以将鼠标悬停在变量名称上,在某些情况下,例如PHP编程时,如果没有调试器,则更容易输出这些变量名称以获取其值
反对此方法的论点“代码行数更多”,“存在不必要的变量”是为了让编译器更轻松而提出的,但没有显著的速度或资源节省。
是否有人能想到任何不应创建仅使用一次的变量名称的情况?