使用奇怪的重复模板模式时的返回类型
我正在使用奇怪的重复模板模式 (CRTP)在我的 C# 项目中,但我遇到了一些问题。从上面的链接中截取的代码:
public abstract class Base<T> where T : Base<T>{
public T FluentMethod() {
return (T)(this);
}
}
public class Derived : Base<Derived> {
}
漂亮!当我尝试做这样的事情时,问题就出现了:
public class SomeClass
{
Base<T> GetItem() { /* Definition */ };
}
SomeClass 应该能够返回基类的任何实现,但是当然 T 在这里没有意义,因为这是在另一个类中。使用 Derived 而不是 T 进行编译,但这不是我想要的,因为我也应该能够返回其他类型的项目,只要它们是从 Base 派生的。此外,GetItem() 可能会根据 SomeClass 对象的状态返回不同类型的对象,因此使 SomeClass 通用也不是解决方案。
我是否在这里遗漏了一些明显的东西,或者在使用 CRTP 时不能完成此操作?
I'm using the curiously recurring template pattern (CRTP) in my C# project, but I'm having some problems. Code snipped from the link above:
public abstract class Base<T> where T : Base<T>{
public T FluentMethod() {
return (T)(this);
}
}
public class Derived : Base<Derived> {
}
Beautiful! The problem arises when I try to do something like this:
public class SomeClass
{
Base<T> GetItem() { /* Definition */ };
}
SomeClass should be able to return any implementation of the Base class, but of course T has no meaning here as this is in another class. Putting Derived instead of T compiles, but this isn't what I want, as I should be able to return items of other types too, as long as they derive from Base. Also, GetItem() might return different typed object depending on the state of the SomeClass object, so making SomeClass generic isn't the solution either.
Am I missing something obvious here, or can't this be done while using the CRTP?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须将方法声明为通用:
要使其成为属性,您必须将类本身声明为通用:
You must declare the method as generic:
To make it a property you must declare the class itself as generic:
不要将公共方法设为泛型,否则类型声明会达到另一个层次。为不同的类型创建一个工厂类,例如“Derived GetDerivedItem()”
Don't make public method as generic, else type declaration reach another level. Make a factory class for different Types like "Derived GetDerivedItem()"