简体   繁体   中英

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?

You can declare your base class using generics, and in your ContactApiModel class just set the T parameter to be ContactApiModel , as the following:

public abstract class BaseApiModel<T> {
    ...
    public abstract T FromJson(string json);
}


public class ContactApiModel : BaseApiModel<ContactApiModel> {
    ...
    public override ContactApiModel FromJson(string json) {
        [...return deserialized object...]
    }
}

For future visitors of this:

A smarter solution would be to not implement that method at all in the corresponding classes and instead use extension methods:

public static class ExtendBaseApiModel
{
    public static string ToJson(this T obj) { /* ... */ }
    public static T FromJson<T>(this T obj, string json) where T : BaseApiModel { /* ... */ }
}

this will allow you to keep your classes nice and clean + free from serialization hazzle.

still .. there are some words to say

How to de -serialize proper

Assuming this is done to provide custom serialization inside the ToJson method and custom deserialization inside the FromJson method, then you should not use your own weirdo methods but rather let the framework do it for you.

For Json.NET , this should be done by utilizing the JsonConverter attribute onto the class and implementing a corresponding JsonConverter somewhere

Fun Fact

Combining the extension methods variant with the upper mentioned JsonConverter, you will be able to just serialize about every object by just calling myobjvar.ToJson(...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM