簡體   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#?

編輯:這個問題的主要目的是更深入地了解 C# 和 OOP。 請記住,我不是試圖用這段代碼解決特定問題,而是試圖了解一切是如何工作的。

我有辦法做到這一點,但我想知道是否還有其他方法可以做到這一點。

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;
    }

}

然后調用它:

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

其中“ApplicationInit”是 ModelBase 的派生 class。

如果相反,我可以打電話給:

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

...並且代碼將能夠告訴派生的 class 是什么。

IDK,也許那是不可能的......

沒有。當您聲明static方法時,它只有一個版本*。 調用ModelBase.Error<ApplicationInit>("")和調用ApplicationInit.Error<ApplicationInit>("")都將編譯為完全相同的字節碼,並且一組好的分析器會將后者標記為警告。

您可以在ApplicationInit中使用新的 static 方法隱藏Error ,但這對於每個新子類都是手動過程。 沒有辦法^比你已經擁有的更概括它。


* 一個泛型方法可以為不同的類型參數產生不同的字節碼,但所有這些方法都是 ModelBase 的ModelBase成員,而不是任何子類。

^ 您可以編寫源生成器來生成這些 static 方法,但這比直接使用通用ModelBase.Error<T>方法要多得多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM