简体   繁体   中英

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); 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.

You can eliminate it by changing BaseClass to a generic class:

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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