2010-02-18 41 views
1

我有一個winform應用程序在室內使用,下面是很常見的。將值分配給控件的變量'空',必須有更好的方法!

  Int32? afhAgreement = null; 
      if (!lkuReveiewAFHAgreement.Text.Equals(string.Empty)) 
      { 
       afhAgreement = (Int32)lkuReveiewAFHAgreement.EditValue; 
      } 
      DateTime? afhAgreementDate = null; 
      if (datAFHAgreementCompleted.Text != String.Empty) 
      { 
       afhAgreementDate = (DateTime?)datAFHAgreementCompleted.EditValue; 
      } 
      Int32? crisisPlan = null; 
      if (!lkuReview6MonthCrisisPlan.Text.Equals(string.Empty)) 
      { 
       crisisPlan = (Int32)lkuReview6MonthCrisisPlan.EditValue; 
      } 
      DateTime? crisisPlanDate = null; 
      if (dat6MonthCrisisPlanReviewed.Text != String.Empty) 
      { 
       crisisPlanDate = (DateTime?)dat6MonthCrisisPlanReviewed.EditValue; 
      } 
      Int32? riskAgreement = null; 
      if (!lkuReviewRiskAssessment.Text.Equals(string.Empty)) 
      { 
       riskAgreement = (Int32)lkuReviewRiskAssessment.EditValue; 
      } 
      DateTime? riskAgreementDate = null; 
      if (!datRiskAssessmentReviewed.Text.Equals(string.Empty)) 
      { 
       riskAgreementDate = (DateTime?)datRiskAssessmentReviewed.EditValue; 
      } 

看到所有這些變量都可以NULL好像這是做這個荒謬的方式。沒有Convert this object and Default to NULL

順便說一句,EditValue是一個對象,雖然我相信我也有同樣的問題,即使我使用控件的Text屬性。

那麼,有沒有更好的方法?這是我可以用Extension Methods簡化嗎?

回答

4

只需添加一些可重複使用的功能...比如:

static T? GetValue<T>(YourControlType control) where T : struct 
{ 
    if (string.IsNullOrEmpty(control.Text)) return null; 
    return (T)control.EditValue; 
} 

然後(例如):

DateTime? crisisPlanDate = GetValue<DateTime>(dat6MonthCrisisPlanReviewed); 

(其中YourControlType是您使用的任何控件string .Textobject .EditValue

+0

所以我會創建一個類似於這個每個控制類型的函數,是否正確? DateTime,LookUp等...... – 2010-02-18 13:22:12

+0

如果您有單一的控件類型,那麼這不是必需的 - 但從問題中不明確。 – 2010-02-18 13:47:06

+0

對不起!是的,我有多種控制類型。在問題'lku'會引用一個LookUp下拉框,'dat'引用一個DateEdit框。還有其他人,我只是試圖保持這個問題過分簡單,以至於人們會回答。 – 2010-02-18 13:54:38

1

這樣的事情..

afhAgreement = (!lkuReveiewAFHAgreement.Text.Equals(string.Empty)) ? (Int32)lkuReveiewAFHAgreement.EditValue : null; 

riskAgreement = (!lkuReviewRiskAssessment.Text.Equals(string.Empty)) ? (Int32)lkuReviewRiskAssessment.EditValue : null;