Jak uprościć ten kod? Drabinka ifów dla różnych typów

0

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 ;)

2

wyrzuć do to osobnej metody i użyj przeciążenia żeby dostarczyć mechanizm dla każdego typu

bool tryParseAndCompare(decimal value) {
  ...
}

bool tryParseAndCompare(double value) {
  ...
}

...
1

Za wiele to nie upraszcza, ale można to zapisać za pomocą Pattern Matching

public static bool IsEquel<T>(T value, string other)
{  
	switch(value)
	{
		case decimal leftValue:
	    {
			return decimal.TryParse(other, out decimal rightValue) && leftValue == rightValue;
	    }
		case float leftValue:
	    {
			return float.TryParse(other, out float rightValue) && leftValue == rightValue;
	    }
		case double leftValue:
	    {
			return double.TryParse(other, out double rightValue) && leftValue == rightValue;
	    }				
	}
	return false;
}
6

Hej, tak na szybko pomyślałem że można spróbować TypeConverterem
pisane na kolanie

bool Compare<T>(T value, string other)
{
    var converter = TypeDescriptor.GetConverter(typeof(T));
    try
    {
        var converted = (T)converter.ConvertFromString(other);
        return converted.Equals(value);
    }
    catch (NotSupportedException)
    {
        return false;
    }
}

1 użytkowników online, w tym zalogowanych: 0, gości: 1