开发者

C# generic - returning objects of the derived class?

开发者 https://www.devze.com 2022-12-24 16:00 出处:网络
public class BaseClass{ public static T Find<T>(object value){ -- db.get<T>(\"params\", 开发者_StackOverflow中文版value);
public class BaseClass{
  public static T Find<T>(object value){
     -- db.get<T>("params", 开发者_StackOverflow中文版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);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消