1、vs中的代码重构快捷方式:Refactor-Extract;
选中两个需要重构的部分完整代码,右击,选中Refactoe-Extract-Extract Method;
该选中的代码会自动形成一个Execute()方法,自己修改方法名就OK啦。
2、下面说一下我的具体代码修改:这个是两个方法中执行了相同的INSERT语句,所以将它整合成一个方法;这样后续有修改或者改动时,会方便很多,也便于代码阅读。
1 //APP端(插入T_UserBookingTraining) 2 public int SubscribeIntentionMajor(int courseId, int shareUserId, string name, string phoneNum, string intentionMajor) 3 { 4 var type = 1; 5 string tidSql = @" 6 IF EXISTS( 7 SELECT tcl.TrainingInstitutionId 8 FROM dbo.T_Course tc 9 LEFT JOIN dbo.T_Class tcl ON tc.ClassId = tcl.Id 10 WHERE tc.Id = @cid) 11 SELECT tcl.TrainingInstitutionId 12 FROM dbo.T_Course tc 13 LEFT JOIN dbo.T_Class tcl ON tc.ClassId = tcl.Id 14 WHERE tc.Id = @cid 15 ELSE 16 SELECT 0"; 17 var tid = DbTopOnline.ExecuteScalar<int>(tidSql, new { cid = courseId }); 18 19 return InsertUserBookingTraining(shareUserId, name, phoneNum, intentionMajor, tid, type); 20 }
1 //官网端(插入T_UserBookingTraining) 2 public int SubscribeIntentionMajorFromWebSite(string phoneNum, int tid) 3 { 4 var shareUserId = 0; 5 var name = phoneNum; 6 var intentionMajor = "来自官网的意向"; 7 var type = 2;
8 return InsertUserBookingTraining(shareUserId, name, phoneNum, intentionMajor, tid, type); 9 }
1 //重构出来的代码(主要执行INSERT操作) 2 private int InsertUserBookingTraining(int shareUserId, string name, string phoneNum, string intentionMajor, int tid, int type) 3 { 4 string userIdSql = @" 5 SELECT 6 tu.Id 7 FROM 8 dbo.T_User tu 9 WHERE 10 tu.TrainingInstitutionId = @tid 11 AND Name = 'admin' 12 AND IsDel=0 13 AND IsUsed=1"; 14 var userId = DbTopManager.ExecuteScalar<int>(userIdSql, new { tid }); 15 16 string sql = @"; 17 IF EXISTS(SELECT * FROM T_UserBookingTraining WHERE Phone = @phoneNum AND TrainingInstitutionId = @tid ) --判断手机号 18 BEGIN 19 UPDATE dbo.T_UserBookingTraining 20 SET Intention = @intentionMajor, UserName = @name 21 WHERE Phone = @phoneNum 22 END 23 ELSE 24 BEGIN 25 INSERT INTO dbo.T_UserBookingTraining 26 ( TrainingInstitutionId , 27 TemplatId , 28 SceneId , 29 Type , 30 UserId , 31 ShareUserId , 32 Phone , 33 UserName , 34 Intention , 35 ProgressStatus , 36 IsDel , 37 IsUsed , 38 CreateTime 39 ) 40 VALUES ( @tid, -- TrainingInstitutionId - int 41 0 , -- TemplatId - int 42 0 , -- SceneId - int 43 @type , -- Type - tinyint 44 @userId , -- UserId - int 45 @uid, -- ShareUserId - int 46 @phoneNum, -- Phone - nchar(11) 47 @name, -- UserName - nvarchar(20) 48 @intentionMajor, -- Intention - nvarchar(60) 49 0 , -- ProgressStatus - tinyint 50 0 , -- IsDel - bit 51 1 , -- IsUsed - bit 52 GETDATE() -- CreateTime - datetime 53 ) 54 END"; 55 return DbTopOnline.Execute(sql, new 56 { 57 userId, 58 uid = shareUserId, 59 name, 60 phoneNum, 61 intentionMajor, 62 tid, 63 type 64 }); 65 }