[英]C# Method in base class that returns derived type
I'm trying to create a method in a base class that would be able to return derived types.我正在尝试在基类中创建一个能够返回派生类型的方法。 It's not necessary that it actually resides in the base class, but I would like to not have to implement the method in all derived classes.
它没有必要实际驻留在基类中,但我不想在所有派生类中实现该方法。
Something like this.像这样的东西。
public class Error
{
protected Error() { }
public string Message { get; protected set; }
public static Error Because(string msg)
{
return new Error() { Message = msg };
}
}
And then I create two derived types:然后我创建了两个派生类型:
public class MyError : Error
public class OtherError : Error
that I'm able to instantiate with Because
without any further implementation.我可以用
Because
实例化而无需任何进一步的实现。
I know I'm able to do an implementation like this:我知道我可以执行这样的实现:
public static T Because<T>(string message)
where T : Error
{
var error = default(T);
error.Message = message;
return error;
}
But then I have to specify the type parameter:但是我必须指定类型参数:
MyError err = Error.Because<MyError>("My error");
or或者
MyError simp = MyError.Because<MyError>("My error");
I would like to be able to call it with something like this:我希望能够用这样的东西来调用它:
MyError myError = MyError.Because("Something went wrong");
OtherError myError = OtherError.Because("Something else went wrong");
Looks like a Curiously recurring template pattern fits here.看起来像一个Curiously recurring 模板模式适合这里。
Like:喜欢:
public abstract class Error<ConcreteError>
where ConcreteError : Error<ConcreteError>, new()
{
protected Error() { }
public string Message { get; protected set; }
public static ConcreteError Because(string msg)
{
return new ConcreteError() { Message = msg };
}
}
public class MyError : Error<MyError> { }
public class OtherError : Error<OtherError> { }
static void Main(string[] args)
{
MyError myError = MyError.Because("Something went wrong");
OtherError myError2 = OtherError.Because("Something else went wrong");
}
The feature you are describing is a return type covariance which is an accepted and championed language feature which will be implemented in one of the next versions of C# language.您所描述的功能是返回类型协方差,它是一种被接受和支持的语言功能,将在 C# 语言的下一个版本之一中实现。 Currently release is planned for C# 9.0.
目前计划为 C# 9.0 发布。
For more details, pls have a look at the corresponding dotnet/csharplang
discussion thread:有关更多详细信息,请查看相应的
dotnet/csharplang
讨论线程:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.