简体   繁体   English

C#generic - 返回派生类的对象?

[英]C# generic - returning objects of the derived class?

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); 在上面的代码中,我如何更改Derived obj = Derived.FindDerived<Derived>(1); to Derived obj = Derived.Find(1); to Derived obj = Derived.Find(1);

If your method signature were something like this 如果您的方法签名是这样的

public static T Find<T>(T value)

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. 但是,根据您给定的签名,编译器无法在不明确说明类型的情况下推断出类型。

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. 以下是Eric Lippert关于类似问题的博客文章。

You can eliminate it by changing BaseClass to a generic class: 您可以通过将BaseClass更改为泛型类来消除它:

public class BaseClass<T> {
    public static T Find(object value){
         -- db.get<T>("params", value);
    }
}

public class Derived: BaseClass<Derived> {

    void someMethod(){
      Derived obj = Derived.Find(1);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM