【发布时间】:2021-02-10 00:01:36
【问题描述】:
编辑:这个问题的主要目的是更深入地了解 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 的派生类。
如果相反,我可以调用:
return ApplicationInit.Error("Failed to retrieve application segment.");
...并且代码将能够告诉派生类是什么。
IDK,也许这不可能……
【问题讨论】:
-
这个方法需要通用吗?您可以创建
ModelBase的私有派生类并返回它。public static ModelBase Error(string errorDescription) -
有 很多 种替代品,但如果有任何一种您认为合适,那就没法说了。这个问题太宽泛了,不适合 Stack Overflow。也就是说,您现在所拥有的似乎是一种合理的“工厂方法”方法,我看不出
ApplicationInit.Error在任何实质上都比Error<ApplicationInit>更可取。 -
Curiously Recurring Template Pattern 可能在这里工作。所以你声明
class ModelBase<T> where T : ModelBase<T>看起来很奇怪但有效 -
你的第二个例子,这个“超酷的方式”可以用Extension Methods实现