简体   繁体   中英

Dart equivalent of Ruby's instance_eval

Ruby has a really neat method called instance_eval that allows evaluating a block of code in the context of a specific instance. This is great because one can use the same block of code in different contexts and get different results based on how the context defines certain methods. Is there something equivalent in Dart? In other words can I take a method from a class and attach and execute it on another instance in another class or even define a method by letting the user pass in the code corresponding to the method. I know some limited form of this is possible to emulate with subclassing.

It seems that there no possibility of doing that in Dart. But you could use several approaches, depending on your needs:

  1. Creating a function with context as an argument of this function:

    someFunction (context, arg1, arg2) { ... }

  2. Using mixins: https://www.dartlang.org/articles/mixins/

  3. Using generics: https://www.dartlang.org/articles/optional-types/#generics

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM