来自 Kotlin documentation页面:
// public final class Gson {
// ...
// public <T> T fromJson(JsonElement json,
// Class<T> classOfT)
// throws JsonSyntaxException {
// ...
在上面的代码片段中,我理解除了 Class<T>
之外的所有内容。事物。我认为它是以下 C# 等价物:
public sealed class Gson
{
public T FromJson<T>(JsonElement json,
System.Type Type)
{
}
}
客户端代码会这样说:
var gson = new Gson();
var customer = gson.FromJson<Customer>(json, typeof(Customer));
但我不能确定,因为整个 System.Type
面对泛型类型参数 T
,参数似乎是多余的在方法定义中。
另外,在该页面的同一位置,class.java
是什么?在以下代码段中?
inline fun <reified T: Any> Gson.fromJson(json):
T = this.fromJson(json, T::class.java)
我假设类 Class
在 Java 中类似于 System.Type
所以如果你想说,typeof(Customer)
,你会说 Customer.class
?对吗?
什么是class.java
?
最佳答案
Java 有通用类型删除:实际类型T
在运行时不可用于代码。由于 Gson 需要知道目标反序列化类型是什么,因此传递 Class<T>
明确标识它。
另一方面,Kotlin 的类型系统比 Java 更强大,并且由于函数是内联的,编译器知道泛型类型实际上是什么(reified
关键字)。构造T::class.java
告诉 Kotlin 编译器确定合适的类型 T
是,然后将类引用内联到 T
.
这种内联重定义本质上是 Kotlin 的语法糖,允许 Kotlin 用户将目标类型的硬编码规范委托(delegate)给编译器的推理。
关于java - 您能否用 C# 代码解释这段代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39010222/