简体   繁体   English

从方法泛型推断类型

[英]Inferring type from method generics

I am from a Java background and I am looking from the equivalent in c# for the following. 我来自Java背景,我从c#的等效语言中寻找以下内容。

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

Such that I can do the following, constraining the parameter and inferring the return type. 这样我就可以执行以下操作,限制参数并推断返回类型。

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

I was hoping something like this would work in c# but I am not sure it will. 我希望这样的东西可以在C#中工作,但我不确定是否可以。

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

And and do this. 并且做到这一点。

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

Is something like this even possible in c#? 在C#中甚至可能发生这种情况吗?

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

Cat cat = reader.Read<Cat>();

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

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