簡體   English   中英

如何為自定義控件或擴展方法創建自定義異常處理程序

[英]How to create custom exception handler for custom controls or extension methods

我正在C#中創建一個擴展方法,以從datagridview檢索一些值。 在這里,如果用戶提供的列名不存在,那么我希望此函數引發一個異常,該異常可以在調用此函數的地方進行處理。 我怎樣才能做到這一點。

   public static T Value<T>(this DataGridView dgv, int RowNo, string ColName)
    {
            if (!dgv.Columns.Contains(ColName))
                throw new ArgumentException("Column Name " + ColName + " doesnot exists in DataGridView.");
            return (T)Convert.ChangeType(dgv.Rows[RowNo].Cells[ColName].Value, typeof(T));
    }

這不是正確的方法。 首先,關於用戶錯誤鍵入內容沒有什么例外。 其次,這種擴展方法很容易被嵌套在某種與數據庫一起工作的代碼中。 必須捕獲異常,因為鍵入錯誤是正常的。 但是,您現在也負擔編寫異常處理程序的負擔,並編寫了一堆可以正確恢復程序狀態的代碼。

驗證用戶輸入應該盡早進行,然后再設置一系列難以停止的代碼。 並且沒有理由在用戶輸入驗證中使用異常,一個簡單的if()語句即可完成工作。

現在,您可以根據需要將throw語句保留在原處,這確實可以提供更好的診斷。 但是永遠不要處理該異常,因為它現在可以診斷代碼中的錯誤。 而且,您無法使用catch子句修復錯誤。

很難理解您的問題,但是聽起來您想拋出一個異常並在調用擴展方法的地方進行處理。 如果是這樣,您就快到了。 您已經在拋出異常,只需在調用站點周圍放置一個try/catch塊即可。

public static T Value<T>(this DataGridView dgv, int RowNo, string ColName)
{
    if (!dgv.Columns.Contains(ColName))
        throw new ArgumentException("Column Name " + ColName + " doesnot exists in DataGridView.");
    return (T)Convert.ChangeType(dgv.Rows[RowNo].Cells[ColName].Value, typeof(T));
}

// Wherever you call the method:
try
{
    dataGridView.Value(rowNumber, columnName);
}
catch (ArgumentException)
{
    // caught the exception
}

這是你想要的?

雖然問題已經回答,但我只建議第二個解決方案。 拋出異常的想法應該是最后的選擇。 您可以使用以下方法實現相同的目的。

public static bool TryGetValue<T>(this DataGridView dgv, int RowNo, 
    string ColName, out T cellValue)
{
    cellValue = default(T);
    if (!dgv.Columns.Contains(ColName))
        return false;
    cellValue = (T)Convert.ChangeType(dgv.Rows[RowNo].Cells[ColName].Value, typeof(T));
    return true;
}

public static void Main(){
int desiredValue;
if(dataGridView.TryGetValue<int>(rowNumber, columnName, out desiredValue)){
    //Use the value
}
else{
    //Value can not be retrieved.
}
}

PS:我尚未在編輯器上鍵入此代碼,因此請原諒任何錯別字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM