Oto fragment kodu:
#region decimal chceck
if (value is decimal)
{
if (!decimal.TryParse(paramStringValue, out decimal paramValue))
{
return false;
}
return paramValue == (decimal)value;
}
#endregion
#region float chceck
if (value is float)
{
if (!float.TryParse(paramStringValue, out float paramValue))
{
return false;
}
return paramValue == (float)value;
}
#endregion
#region double chceck
if (value is double)
{
if (!double.TryParse(paramStringValue, out double paramValue))
{
return false;
}
return paramValue == (double)value;
}
#endregion
I tak, to jest tylko fragment... Metoda idzie w tym stylu przez jeszcze kilka typów, a każdy if różni się tylko typem. Co można z tym zrobić?
Myślałam, by wykorzystać generyki na zasadzie:
private bool Compare<T>(T value, string other)
{
if (!typeof(T).TryParse(other, out typeof(T) otherValue))
{
return false;
}
return otherValue == value;
}
...ale typeof(T) oczywiście nie ma metody TryParse ;)