我想在 C# 中创建一个接口(interface),该接口(interface)定义一个始终返回实现类对象的方法,因此:
public interface IParser {
IParser Parse(string s);
}
public class Parser : IParser {
public Parser Parse(string s) {
return new Parser(s);
}
}
我可以强制一个实现类返回一个它自己类型的对象吗?如果可能,那么如何?还是泛型就是这里的答案?
NB: The code is just an illustration, not something that's supposed to run.
最佳答案
泛型就是这里的答案。
public interface IParser<T> where T:IParser<T> {
T Parse(string s);
}
public class Parser : IParser<Parser> {
public Parser Parse(string s) {
return new Parser(s);
}
}
关于c# - 我可以强制一个实现类返回一个它自己类型的对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1688289/