镖。使用泛型 T 和 Object 有什么区别?
Dart. What the difference between using generic T and Object?
我试图了解使用泛型和对象之间的区别。我已经阅读了一些与 Java 相关的答案(请参阅 ),我发现差异非常明显 - function/method returns (a) Object if we use Object as输入参数类型和 (b) 实际类型,如果我们使用泛型 T。但是 Dart 有它自己的行为,这种情况不适用。让我们看例子:
main() {
// expect Object type
print((new TestObject()).Pass('string').runtimeType);
// expect String type
print((new TestGeneric()).Pass('string').runtimeType);
// both output String type
}
class TestObject {
Object Pass(Object element)
=> element;
}
class TestGeneric<T> {
T Pass(T element)
=> element;
}
我不太了解如何使用面向对象的思想。所以,请问有人能解释一下使用泛型而不是 Object base 的区别吗 class.
当只有类型在几个 class 之间发生变化时,泛型允许避免许多声明。在您的示例中,可以删除 TestObject
class 并在出现 TestObject
的任何地方替换为 TestGeneric<Object>
。
您对 (new TestObject()).Pass('string').runtimeType
的预期输出不正确。 runtimeType
returns 对象的类型。这里 'string'
是 returned,所以 'string'.runtimeType
是 String
。
我试图了解使用泛型和对象之间的区别。我已经阅读了一些与 Java 相关的答案(请参阅 ),我发现差异非常明显 - function/method returns (a) Object if we use Object as输入参数类型和 (b) 实际类型,如果我们使用泛型 T。但是 Dart 有它自己的行为,这种情况不适用。让我们看例子:
main() {
// expect Object type
print((new TestObject()).Pass('string').runtimeType);
// expect String type
print((new TestGeneric()).Pass('string').runtimeType);
// both output String type
}
class TestObject {
Object Pass(Object element)
=> element;
}
class TestGeneric<T> {
T Pass(T element)
=> element;
}
我不太了解如何使用面向对象的思想。所以,请问有人能解释一下使用泛型而不是 Object base 的区别吗 class.
当只有类型在几个 class 之间发生变化时,泛型允许避免许多声明。在您的示例中,可以删除 TestObject
class 并在出现 TestObject
的任何地方替换为 TestGeneric<Object>
。
您对 (new TestObject()).Pass('string').runtimeType
的预期输出不正确。 runtimeType
returns 对象的类型。这里 'string'
是 returned,所以 'string'.runtimeType
是 String
。