结论:
    with 可以赋予类成员变量和方法,
    不会覆盖原类的同名成员变量和方法
    with 可以多个类,后面的类会覆盖前面的类

    示例1:

    1. class Mark{
    2. String name = "James with mark";
    3. void introduceSelf() {
    4. print(name);
    5. }
    6. }
    7. class Person with Mark {
    8. }
    9. void main() {
    10. Person().introduceSelf();
    11. print(Person().name);
    12. }
    13. 输出:
    14. James with mark
    15. James with mark

    从输出结果可以看出 Persion获得Mark的成员变量和方法

    示例2:

    1. class Mark{
    2. String name = "James with mark";
    3. void introduceSelf() {
    4. print(name);
    5. }
    6. }
    7. class Person with Mark {
    8. String name = "James";
    9. int age = 18;
    10. void introduceSelf() {
    11. print(name);
    12. print('I am $age years old');
    13. }
    14. }
    15. void main() {
    16. Person().introduceSelf();
    17. }
    18. 输出
    19. James
    20. I am 18 years old

    从输出结果可以看出,with 并没有覆盖掉Persion类的成员变量和方法,也就是说不会影响原有类的成员变量和方法。

    示例3:

    1. class Mark{
    2. String name = "James with mark";
    3. void introduceSelf() {
    4. print(name);
    5. }
    6. }
    7. class Person with Mark {
    8. String name = "James";
    9. int age = 18;
    10. // void introduceSelf() {
    11. // print(name);
    12. // print('I am $age years old');
    13. // }
    14. }
    15. void main() {
    16. Person().introduceSelf();
    17. }
    18. 输出
    19. James

    从输出结果可以看出,Persion通过with 获得了 Mark的 introduceSelf() 方法,并且成员变量name没有被覆盖。等同于如下:

    1. class Person with Mark {
    2. String name = "James";
    3. int age = 18;
    4. void introduceSelf() {
    5. print(name);
    6. }
    7. }

    示例4:

    1. class Mark{
    2. String name = "James with mark";
    3. void introduceSelf() {
    4. print(name);
    5. }
    6. }
    7. class MarkB{
    8. String name = "James with markb";
    9. void introduceSelf() {
    10. print(name);
    11. }
    12. }
    13. class Person with Mark ,MarkB{
    14. }
    15. class PersonB with MarkB,Mark{
    16. }
    17. void main() {
    18. Person().introduceSelf();
    19. print(Person().name);
    20. PersonB().introduceSelf();
    21. print(PersonB().name);
    22. }
    23. 输出结果:
    24. James with markb
    25. James with markb
    26. James with mark
    27. James with mark

    从输出结果可以看出,with 有先后顺序,后with的类会覆盖之前的。