简体   繁体   English

是否有另一种方法可以基于 ZD7EFA560FBE7D39D724 中的派生 class 类型更改抽象 class 的 static 方法的返回类型?

[英]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.编辑:这个问题的主要目的是更深入地了解 C# 和 OOP。 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.其中“ApplicationInit”是 ModelBase 的派生 class。

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. ...并且代码将能够告诉派生的 class 是什么。

IDK, maybe that's not possible... IDK,也许那是不可能的......

No. When you declare a static method, there is only one version* of it.没有。当您声明static方法时,它只有一个版本*。 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.调用ModelBase.Error<ApplicationInit>("")和调用ApplicationInit.Error<ApplicationInit>("")都将编译为完全相同的字节码,并且一组好的分析器会将后者标记为警告。

You can shadow Error with a new static method in ApplicationInit , but that would be a manual process for each new subclass.您可以在ApplicationInit中使用新的 static 方法隐藏Error ,但这对于每个新子类都是手动过程。 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. * 一个泛型方法可以为不同的类型参数产生不同的字节码,但所有这些方法都是 ModelBase 的ModelBase成员,而不是任何子类。

^ 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. ^ 您可以编写源生成器来生成这些 static 方法,但这比直接使用通用ModelBase.Error<T>方法要多得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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