jeudi 16 septembre 2021

C# Generic Return Type of Calling Object Type

I am making a class to abstract some functionality that I will be using in multiple other classes in my project. This class converts objects to and from JSON and also deep copies objects.

[Serializable]
public abstract class Serializable
{
    public T Copy<T>()
    {
        return Deserialize<T>(Serialize());
    }

    public string Serialize()
    {
        return JsonConvert.SerializeObject(this);
    }

    public static T Deserialize<T>(string json)
    {
        return JsonConvert.DeserializeObject<T>(json);
    }
}

This code works as intended; however, I would like to simplify the syntax of the Copy and Desirialize functions. Currently, a call looks like this copy = descendantClassInstance.Copy<descendantClass>() which is wordy and also leaves room for error in that copy = otherdescendantClassInstance.Copy<descendantClass>() would compile but yield an error at runtime. I would prefer the return type be automatically inferred based on the type of the calling object, like copy = descendantClassInstance.Copy(), without overriding the Copy or Desirialize method in each descendant class.

How can I do this?





Aucun commentaire:

Enregistrer un commentaire