我想添加我自己的方法到几个Dart类 [英] I want to add my own methods to a few Dart Classes

查看:549
本文介绍了我想添加我自己的方法到几个Dart类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试简单地扩展Map类失败,因为List是一个接口,无法扩展,但必须实现。



目标只是在某些现有类之上添加几个方法,例如:



add_unique(item)其中,我只想追加,如果该项目不存在。这可以很好地通过和append!= null逻辑与List.indexOf(item)!= -1(其中-1不是Found)完成。这将是一个很好的和容易理解的例子?



但是,如何完成这个在最短,总体开销最小的方式?我想我可以松散键入 - 至少从开始。



还有其他方法我想添加和/或修改,如.add()方法对于Map类。



我没有处理接口多年,我认为可能只是一个更简单的方法开始在这一边我的项目。



谢谢!

解决方案

问题也。目前最好的解决方法是创建一个转发所有方法调用的类。例如:
https:// github。 com / dart-lang / html5lib / blob / master / lib / src / list_proxy.dart



然后你可以继承ListProxy并覆盖或添加任何方法



如果人们发现这很有用,也许我们可以把它放在自己的pub包中。我希望我们可以得到dart:core fixed,虽然,所以它支持所有的核心集合类继承。



顺便说一下,如果你试图在Map中重载一个方法要容易得多:你可以 import'dart:coreimpl'; 并扩展 HashMapImplementation / p>

My attempt to simply 'Extend' the Map class fails because List is an interface and cannot be extended but must be implemented.

The goal was simply to add a few methods on top of some existing class such as:

List.add_unique(item) where I only want to append if the item does not already exist. This can be done nicely by and-ing the append !=null logic with List.indexOf(item) != -1 (where -1 is notFound). This would be a good and easy to understand example?

But, how to accomplish this in the shortest, least overall overhead sort of way? I think I would be OK with loose typing - at least to start with.

There are other methods I wish to add and or modify such as an .add() method for the Map class.

I have not dealt with interfaces for many years and I'm thinking there might just be a much easier way overall to get started on this side of my project.

Thanks!

解决方案

I've hit this problem too. The best workaround at the moment is to create a class that forwards all of the method calls. Something like: https://github.com/dart-lang/html5lib/blob/master/lib/src/list_proxy.dart

Then you can inherit from ListProxy and override or add whatever methods you need.

If people find this useful enough, maybe we can put it in its own pub package. I'm hoping we can get dart:core fixed, though, so it supports inheritance from all of the core collection classes.

By the way, if you're trying to override a method in Map it's much easier: you can import 'dart:coreimpl'; and extend HashMapImplementation.

这篇关于我想添加我自己的方法到几个Dart类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆