[英]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.