C# 从方法泛型推断类型
我来自Java背景,我从c#中的等价物中寻找以下内容C# 从方法泛型推断类型,c#,java,generics,C#,Java,Generics,我来自Java背景,我从c#中的等价物中寻找以下内容 public interface Reader { <T> T read(Class<? extends T> type); } 我本来希望类似的东西在c#中能起作用,但我不确定它会起作用 public interface Reader { T Read<T>(); } 公共接口读取器{ T Read(); } 然后做这个 public class TypeReader : Reader
public interface Reader {
<T> T read(Class<? extends T> type);
}
我本来希望类似的东西在c#中能起作用,但我不确定它会起作用
public interface Reader {
T Read<T>();
}
公共接口读取器{
T Read();
}
然后做这个
public class TypeReader : Reader {
public T Read<T>() {
Type type = T.GetType();
...
}
}
公共类类型读取器:读取器{
公众阅读{
Type Type=T.GetType();
...
}
}
在c#?中也可能出现类似的情况吗?是的,但是您需要
typeof(T)
,而不是T.GetType()
,并且:
Cat cat = reader.Read<Cat>();
Cat=reader.Read();
Cat cat = reader.Read<Cat>();