Domanda

Attualmente sto eseguendo il refactoring del codice per sostituire Convert.To's in TryParse.

Ho trovato il seguente bit di codice che sta creando e assegnando una proprietà a un oggetto.

List<Person> list = new List<Person>();

foreach (DataRow row in dt.Rows)
{
     var p = new Person{ RecordID = Convert.ToInt32(row["ContactID"]) };

     list.Add(p);
}

Quello che ho trovato in sostituzione è:

var p = new Person { RecordID = Int32.TryParse(row["ContactID"].ToString(), out RecordID) ? RecordID : RecordID };

Qualche pensiero, opinione, alternativa a quello che ho fatto?

È stato utile?

Soluzione

Scrivi un metodo di estensione.

public static Int32? ParseInt32(this string str) {
    Int32 k;
    if(Int32.TryParse(str, out k))
        return k;
    return null;
}

Altri suggerimenti

Userei un'implementazione alternativa TryParse che restituisce un int? :

public static int? TryParseInt32(string x)
{
    int value;
    return int.TryParse(x, out value) ? value : (int?) null;
}

Quindi puoi scrivere:

var p = new Person { RecordID = Helpers.TryParseInt32(row["ContactID"].ToString()) ?? 0 };

(O utilizzare un valore predefinito diverso, se lo si desidera, in entrambi i casi sarà visibile nel codice.)

Suggerisco di separare la parte TryParse dall'inizializzatore. Sarà più leggibile.

int recordId;
Int32.TryParse(row["ContactID"].ToString(), out recordID)

foreach (DataRow row in dt.Rows)
{
     var p = new Person{ RecordID = recordId };
     list.Add(p);
}
private static void TryToDecimal(string str, Action<decimal> action)
{
        if (decimal.TryParse(str, out decimal ret))
        {
            action(ret);
        }
        else
        {
            //do something you want
        }
}

TryToDecimal(strList[5], (x) => { st.LastTradePrice = x; });
TryToDecimal(strList[3], (x) => { st.LastClosedPrice = x; });
TryToDecimal(strList[6], (x) => { st.TopPrice = x; });
TryToDecimal(strList[7], (x) => { st.BottomPrice = x; });
TryToDecimal(strList[10], (x) => { st.PriceChange = x; });
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top