简体   繁体   中英

Is there another way to change the return type of a static method of an abstract class based on the derived class type in C#?

Edit: The main purpose of this question is to gain a deeper understanding of C# and OOP in general. Please keep in mind that I'm not trying to solve a specific problem with this code, but instead just trying to understand how everything works.

I have a way to do this, but I'm wondering if there is another way to do it.

public abstract class ModelBase
{

    private const string ERROR = "Error";

    public string Status { get; set; }
    public string StatusDescription { get; set; }

    public static T Error<T>(string errorDescription)
        where T : ModelBase, new()
    {
        var model = new T
        {
            Status = ERROR,
            StatusDescription = errorDescription
        };
        return model;
    }

}

And then to call it:

return ModelBase.Error<ApplicationInit>("Failed to retrieve application segment.");

Where "ApplicationInit" is a derived class of ModelBase.

What would be super cool is if instead, I could call:

return ApplicationInit.Error("Failed to retrieve application segment.");

...And the code would be able to just tell what the derived class is.

IDK, maybe that's not possible...

No. When you declare a static method, there is only one version* of it. The call ModelBase.Error<ApplicationInit>("") and the call ApplicationInit.Error<ApplicationInit>("") will both compile to the exact same bytecode, and a good set of analyzers will flag the latter with a warning.

You can shadow Error with a new static method in ApplicationInit , but that would be a manual process for each new subclass. There is no way^ to generalize it more than you already have.


* A generic method can produce different bytecode for different type parameters, but all such methods are static members of ModelBase , and not any subclass.

^ You could write a source generator to generate these static methods, but that is a lot more work than just using the generic ModelBase.Error<T> method directly.

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