簡體   English   中英

如何在有機會引發異常之前將null值轉換為string.empty?

[英]How can I convert a null value to string.empty before it has a chance to throw an exception?

我有以下代碼將先前的值輸入到DataGridView單元格中。 如果位於第0行且col 2或更大,則val位於左側,否則位於正上方的值:

private void dataGridViewPlatypi_CellEnter(object sender, DataGridViewCellEventArgs args)
{
    // TODO: Fails if it sees nothing in the previous cell
    string prevVal = string.Empty;
    if (args.RowIndex > 0)
    {
        prevVal = dataGridViewPlatypi.Rows[args.RowIndex - 1].Cells[args.ColumnIndex].Value.ToString();
    } else if (args.ColumnIndex > 1)
    {
        prevVal = dataGridViewPlatypi.Rows[args.RowIndex].Cells[args.ColumnIndex-1].Value.ToString();
    }
    dataGridViewPlatypi.Rows[args.RowIndex].Cells[args.ColumnIndex].Value = prevVal;
}

只要有一個值得觀察和復制的價值,這就很好。 如果該單元格為空,則得到:

用戶代碼未處理System.NullReferenceException
Message =對象引用未設置為對象的實例。

我猜想這是使用null合並運算符的機會,但是(假設我的猜測很好),那我該如何實現呢?

嘗試這樣的事情:

string s = SomeStringExpressionWhichMightBeNull() ?? "" ;

簡單!

假設Value為空(您的帖子中並不完全清楚),您可以這樣做

object cellValue = 
    dataGridViewPlatypi.Rows[args.RowIndex - 1].Cells[args.ColumnIndex].Value;
prevValue = cellValue == null ? string.Empty : cellValue.ToString()

使用如下方法:

public static class MyExtensions
{
    public static string SafeToString(this object obj)
    {
        return (obj ?? "").ToString();
    }
}

那么您可以像這樣使用它:

object obj = null;

string str = obj.SafeToString();

或以您的代碼為例:

prevVal = dataGridViewPlatypi.Rows[args.RowIndex - 1].Cells[args.ColumnIndex].Value.SafeToString();

這將創建一個擴展方法,因此,如果為擴展類在所有對象中的名稱空間添加using ,則在intellisense中將顯示具有SafeToString方法。 該方法實際上不是實例方法,它只是顯示為一個實例,因此,如果對象為null,則不會生成null引用異常,而只是將null傳遞給該方法,該方法會將所有null值視為空字符串。

暫無
暫無

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

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