mardi 25 septembre 2018

Is there a way to specify "type of current class" in a C# method signature?

I'm trying to define an abstract class which other classes will extend, and they have to be able to serialize themselves to JSON and deserialize from JSON. I want to write the abstract class something like this:

public abstract class BaseApiModel {
    public abstract string ToJson();
    public abstract T FromJson(string json);
}

... where T is the type of the current class. I would then write an extending class like this:

public class ContactApiModel : BaseApiModel {
    public string ContactName { get; set; }
    [...other properties...]

    public override string ToJson() {
        [...return serialized JSON string...]
    }

    public override ContactApiModel FromJson(string json) {
        [...return deserialized object...]
    }
}

Of course this doesn't work because T in the abstract class isn't defined. But is there some way I can write "this method has to return the type of the current class" in C#? Do I just going to have to make it return object? Or am I approaching this wrong and there's a better way to structure it?

Aucun commentaire:

Enregistrer un commentaire