Usando TryParse para Definição de objeto valores de propriedade
-
08-07-2019 - |
Pergunta
Atualmente estou refatoração de código para substituir Convert.To da TryParse.
Eu me deparei com o seguinte trecho de código que é criar e atribuir uma propriedade a um 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);
}
O que eu vim acima com como um substituto é:
var p = new Person { RecordID = Int32.TryParse(row["ContactID"].ToString(), out RecordID) ? RecordID : RecordID };
Qualquer pensamentos, opiniões, alternativas para o que eu fiz?
Solução
Escrever um método de extensão.
public static Int32? ParseInt32(this string str) {
Int32 k;
if(Int32.TryParse(str, out k))
return k;
return null;
}
Outras dicas
Eu usaria uma TryParse
implementação alternativa que retorna um int?
:
public static int? TryParseInt32(string x)
{
int value;
return int.TryParse(x, out value) ? value : (int?) null;
}
Em seguida, você pode escrever:
var p = new Person { RecordID = Helpers.TryParseInt32(row["ContactID"].ToString()) ?? 0 };
(Ou use um valor padrão diferente, se você quiser -. De qualquer maneira vai ser visível em seu código)
Eu sugiro separar a parte TryParse de inicializador. Vai ser mais legível.
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 em: CC-BY-SA com atribuição
Não afiliado a StackOverflow