0

I've a bunch of XML files that are deserialized into different class objects. Instead of having separate methods for each one I'd like to have a single method that can handle all of them. I believe I can do this using the generic type T and interfaces. I've read up on the basic principles of interfaces and type generics and have written the code below, and I'm hoping someone could offer feedback.

public interface ILoader < T >
{
    T Load(string path);
}

public XMLReader < T > : ILoader < T >
{
    public T Load(string path)
    {
        T obj;

        try
        {
            XmlSerializer serializer = new XmlSerializer( typeof( T ) );
            FileStream stream = new FileStream( path, FileMode.Open );
            obj = serializer.Deserialize( stream ) as T;
            stream.Close();
        }
        catch
        {
            Debug.LogWarning( "Could not open " + FileName );
        }
        
        return obj;
    }
}

XMLReader<People> r = new XMLReader<People>(); r.Load("People.xml");

Ken White
  • 123,280
  • 14
  • 225
  • 444
Anthony
  • 301
  • 1
  • 2
  • 13
  • what error do you get? i think you'd better define some base class(constraint) for T. – Lei Yang Mar 14 '22 at 02:52
  • @LeiYang I've not yet run it and won't be able to for a few days. I just wanted to ask to make sure nothing was wrong. Sorry if it's frowned upon to ask pre-emptively. – Anthony Mar 14 '22 at 03:00

0 Answers0