2013-07-11 28 views
4

我想從WPF複製代碼的WinForms(此代碼裏面WPF)不能隱式地從對話結果轉換爲bool

public static bool? ShowSettingsDialogFor(ICustomCustomer) 
{ 
    if (cust is BasicCustomer) 
    { 
     return (new BCustomerSettingsDialog()).ShowDialog(); 
    } 
} 

我收到編譯錯誤消息

不能隱式地將類型'System.Windows.Forms.DialogResult'轉換爲 'bool?'

+2

爲什麼要返回'DialogResult'?錯誤消息清楚地表明:_您將布爾值定義爲此方法的返回值,但您要返回DialogResult的實例。到底是什麼?_顯然你可能需要使用'DialogResult'枚舉返回一個布爾值。 –

回答

11

變化,要

return (new BCustomerSettingsDialog()).ShowDialog() == DialogResult.OK; 
7

的原因是,在Windows窗體中,ShowDialog方法返回一個DialogResult枚舉值。可能值的範圍取決於您可以使用哪些按鈕,並且它們的bool?轉換可能取決於它們在應用程序中的含義。以下是一些處理幾種情況的通用邏輯:

public static bool? ShowSettingsDialogFor(ICustomCustomer) 
{ 
    if (cust is BasicCustomer) 
    { 
     DialogResult result = (new BCustomerSettingsDialog()).ShowDialog(); 

     switch (result) 
     { 
      case DialogResult.OK: 
      case DialogResult.Yes: 
       return true; 

      case DialogResult.No: 
      case DialogResult.Abort: 
       return false; 

      case DialogResult.None: 
      case DialogResult.Cancel: 
       return null; 

      default: 
       throw new ApplicationException("Unexpected dialog result.") 
     } 
    } 
} 
相關問題