08.Dart - 类型定义

个人学习用
不严谨
学习的话请看别的博客

类型定义

//1.定义类型 Compare
typedef Compare = int Function(Object a, Object b);

class Test {
  //2.初始化类型
  Compare compare;

  Test(this.compare);
}

void main() {
  /**
   * 类型定义
   * 就是利用 typedef 显示的保留要传递的 函数类型信息
   */

  //3.简单的实现类型方法
  int sort(Object a, Object b) {
    return a.hashCode - b.hashCode;
  }

  Test test = Test(sort);

  print(test.compare is Function); //true
  print(test.compare is Compare); //true
  print(test.compare is Object); //true
  print(test.compare is Comparator); //true
  print(test.compare is int); //false
}

类型定义和泛型

typedef Compare<T> = int Function(T a, T b);

void main() {
  /**
   * 类型定义和泛型
   *
   */
  int sort(int a, int b) {
    return a - b;
  }

  print(sort is Compare<int>); //true
  print(sort is Compare); //不加泛型为 false
}

类型定义自己练习的

typedef Comp<int, String> = int Function(Map<int, String> map, int i);

void main() {
  int test(Map<int, String> map, int i)=> map[i].paserInt() + i;

  print(test is Comp);//false
  print(test is Comp<int, String>);//true


}

/**
 * 使用Extension扩展
 */
extension TestExtension on String {
  int paserInt() {
    return int.parse(this);
  }
}
发布了33 篇原创文章 · 获赞 6 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/zlhyy666666/article/details/104581229