Home > Software design >  How to rewrite methods to be a generic one?
How to rewrite methods to be a generic one?

Time:07-18

I'm going to extract values from attributes of XML XElement, the types of these values are int, double, bool and string, below are the methods for this task, how can I rewrite them to be a generic one? And how to add constraints?

private int GetIntFromAttribute(XElement element, string attributeName)
{
    if (element.Attribute(attributeName) != null)
    {
        int.TryParse(element.Attribute(attributeName).Value, out var intValue);
        return intValue;
    }
    return 0;
}

private double GetDoubleFromAttribute(XElement element, string attributeName)
{
    if (element.Attribute(attributeName) != null)
    {
        double.TryParse(element.Attribute(attributeName).Value, out var doubleValue);
        return doubleValue;
    }
    return 0;
}

private bool GetBoolFromAttribute(XElement element, string attributeName)
{
    if (element.Attribute(attributeName) != null)
    {
        bool.TryParse(element.Attribute(attributeName).Value, out var boolValue);
        return boolValue;
    }
    return false;
}

private string GetStringFromAttribute(XElement element, string attributeName)
{
    if (element.Attribute(attributeName) != null)
    {
        return element.Attribute(attributeName).Value;
    }
    return string.Empty;
}

CodePudding user response:

You can use tests of the form if (typeof(T) == typeof(String)) to call the correct TryParse method.

I assume you know where to put the T and <T>: private T GetFromAttribute<T>(XElement...

CodePudding user response:

You may need to keep different methods for different type when using XXX.TryParse methods.

You could have one method that accepts different types and then switches on the type an calls an appropriate TryParse but you cannot solve the XXX.TryParse problem purely with generics.

  • Related