Pregunta

Actualmente estoy refactorizando el código para reemplazar Convert.To's por TryParse.

He encontrado el siguiente bit de código que está creando y asignando una propiedad a un objeto.

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

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

     list.Add(p);
}

Lo que se me ocurrió como reemplazo es:

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

¿Alguna idea, opinión, alternativa a lo que he hecho?

¿Fue útil?

Solución

Escriba un método de extensión.

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

Otros consejos

Usaría una implementación alternativa TryParse que devuelve un int? :

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

Entonces puedes escribir:

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

(O use un valor predeterminado diferente, si lo desea, de cualquier manera será visible en su código).

Sugiero separar la parte TryParse del inicializador. Será más legible.

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; });
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top