从方法泛型中推断类型

时间:2010-04-26 22:25:07

标签: c# java generics

我来自Java背景,我正在从c#中的等价物中寻找以下内容。

public interface Reader {
   <T> T read(Class<? extends T> type);
}

这样我可以执行以下操作,约束参数并推断返回类型。

Cat cat = reader.read(Cat.class);
Dog dog = reader.read(Dog.class);

我希望这样的东西在c#中起作用,但我不确定它会不会。

public interface Reader {
   T Read<T>();
}

而且这样做。

public class TypeReader : Reader {
   public T Read<T>() {
      Type type = T.GetType();
      ...
   }
}

在c#中是否可以这样?

1 个答案:

答案 0 :(得分:5)

是的,但您需要typeof(T),而不是T.GetType(),并且:

Cat cat = reader.Read<Cat>();
相关问题