简体   繁体   English

强制Dart类型实现接口

[英]Enforcing that a Dart type implements an interface

I have a map of strings to types in Dart eg animals = <String, Type>{'cat':CatType, 'dog':DogType} which I modify at runtime. 我在Dart中有一个字符串到类型的映射,例如,我在运行时修改的animals = <String, Type>{'cat':CatType, 'dog':DogType} Is there a way to ensure that types added to this map implement a particular interface, either at compile-time or runtime? 有没有一种方法可以确保添加到此映射的类型在编译时或运行时实现特定的接口? Something like 就像是

animals = <String, Type<? implements AnimalType>>{...}

or during runtime, 或在运行时

void register(name, type):
  if type implements AnimalType:
    animals[name] = type

No, not really. 不,不是。

The Type class isn't generic, so you can't have a constrain on that. Type类不是通用的,因此您不能对此加以限制。

You can use the dart:mirrors library to check whether a Type object represents a class that implements another type, but it's most likely not worth the effort. 您可以使用dart:mirrors库来检查Type对象是否表示实现了另一种类型的类,但这很不值得。

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

相关问题 返回实现接口的方法类型 - Return type of method that implements an interface 测试该通用类型实现一个接口并使用该接口 - Testing that generic type implements an interface and using that interface Kotlin Pass输入可实现参数化接口的类型 - Kotlin Pass in a type that implements a parameterized interface 确保类型在 Go 编译时实现接口 - Ensure a type implements an interface at compile time in Go 实现接口的类的类型是什么 - What is the type of a class which implements a interface 如何确定Type是否在Java中实现接口? - How to find out if a Type implements an interface in Java? 接口字段应具有实现该接口的类的类型-typescript - Interface field should have type of the class that implements that interface - typescript 检查类型是否在不考虑泛型类型参数的情况下实现泛型接口 - Check if a type implements a generic interface without considering the generic type arguments TypeScript Class 使用联合类型字段实现接口导致错误 (2322) - TypeScript Class Implements Interface with Union Type Field results in Error (2322) 为什么我不能将一个项目转换为泛型类型——其中泛型类型是一个接口,并且在检查该项目是否实现了所述接口之后? - Why can't I cast an item to a generic type — where the generic type is an interface, and after checking that the item implements said interface?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM