【问题标题】:Does Dart have extension methods like c#?Dart 有像 c# 这样的扩展方法吗?
【发布时间】:2013-07-26 17:33:47
【问题描述】:

你可以在 dart 中创建扩展方法吗?就像你可以在 C# 中一样,例如:

void swap(this CssClassSet ccs, String oldClass, String newClass)
{
    ccs.remove(oldClass);
    ccs.add(newClass);
}

用 Dart 可以做这种事情吗?我想扩展 CssClassSet 以拥有 swap(String oldClass, String newClass) 方法。

【问题讨论】:

    标签: extension-methods dart


    【解决方案1】:

    6 年后,扩展功能终于出现了: https://github.com/dart-lang/language/issues/41#issuecomment-539251446

    它们将包含在 dart 2.6 中

    【讨论】:

      【解决方案2】:

      【讨论】:

      • Rejected 在这种情况下,这是不明智的。这降低了吸引力。 Accepted 在这种情况下没有任何意义。请阅读本期的 Gilad Bracha cmets Add C#-style extension methods
      • 有一个更新,现在讨论转移here
      【解决方案3】:

      是的,这是introduced in Dart 2.6

      语法如下:

      extension YourExtension on YourClass {
        void yourFunction() {
          this.anyMember(); // You can access `anyMember` of `YourClass` using `this`.
          anyMember(); // You can access `anyMember` of `YourClass` without `this`.
        }
      }
      
      void main() {
        YourClass yourVariable;
      
        yourVariable.yourFunction(); // valid
      }
      

      您还可以扩展类型,例如 int:

      void main() {
        5.fancyPrint();
        3.minusThree; // returns 0
      }
      
      extension FancyInt on int {
        void fancyPrint() => print('The magic number is $this.');
      
        int get minusThree => this - 3;
      }
      

      你可以learn more here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-25
        • 1970-01-01
        • 2013-06-14
        • 1970-01-01
        • 2014-09-10
        • 2021-10-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多