0

Context: A non-intrusive way to reload objects when their description file is changed

enter image description here


Focus: adding dynamic reloading of objects with minimal changes to the existing codebase

Function called by FileSystemWatcher or alike:

void OnFileChanged(string filename, ...)
{
  var old3 = GetAssetByFilename(filename);
  var new3 = LoadAsset(filename);
  ...
  Utils.CopyFields(new3, old3);
  ...
}

Notes:

  • Cloning won't work because all objects would point to the old copy
  • There are multiple multiple similar lists of assets
  • Changing LoadAsset function is a no-go, there are multiple Load* functions to change
  • Changing Asset clases is no-go
  • Copying has to include private fields, etc.

Question: How to copy fields automatically (or is there a better way to do this)?

Community
  • 1
  • 1
JBeurer
  • 1,707
  • 3
  • 19
  • 38

1 Answers1

2

This seems to do the job:

public static class Utils 
{
    public static void CopyFields<T>(T source, T destination)
    {
        var fields = source.GetType().GetFields();
        foreach(var field in fields)
        {
            field.SetValue(destination, field.GetValue(source));    
        }            
    }
}
JBeurer
  • 1,707
  • 3
  • 19
  • 38
  • That's cloning... e.g. all references would point to the "old copy" – Peter Ritchie Mar 06 '14 at 20:58
  • Cloning would be if a new object was created. This function just copies the fields. In use it would copy fields from newly loaded object into the old object so that the references to the old object would still remain intact. – JBeurer Mar 06 '14 at 21:01
  • "cloning" as described by the OP--which he didn't want. – Peter Ritchie Mar 06 '14 at 21:07