C# 泛型 - 返回派生类的对象?
public class BaseClass{
public static T Find<T>(object value){
-- db.get<T>("params", value);
}
}
public class Derived: BaseClass{
}
...
void someMethod(){
Derived obj = Derived.Find<Derived>(1);
}
在上面的代码中,如何将 Derived obj = Derived.FindDerived
更改为 Derived obj = Derived.Find(1);
public class BaseClass{
public static T Find<T>(object value){
-- db.get<T>("params", value);
}
}
public class Derived: BaseClass{
}
...
void someMethod(){
Derived obj = Derived.Find<Derived>(1);
}
In the above code how do I change Derived obj = Derived.FindDerived<Derived>(1);
to Derived obj = Derived.Find(1);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的方法签名是这样的
那么您可以省略方法调用中的类型。但是,根据您给定的签名,如果您没有明确说明,编译器将无法推断出类型。
If your method signature were something like this
Then you could omit the type in the method call. However, from your given signature, the compiler is unable to infer the type without you stating it explicitly.
在许多情况下,编译器可以识别类型参数,并且可以省略它们,但并非在所有情况下都是如此。我认为返回值只是不支持的情况之一,因为返回值不是方法签名的一部分。
这里是 Eric Lippert 关于类似问题的博客文章。
In many cases compiler can identify type parameters and they can be omitted but not in all cases. I think return value is just one of the not supported cases becase return value is not a part of the method signature.
Here is Eric Lippert's blog post on similar issue.
您可以通过将 BaseClass 更改为泛型类来消除它:
You can eliminate it by changing BaseClass to a generic class: