【问题标题】:why we should use static keyword in dart in place of abstract?为什么我们应该在飞镖中使用静态关键字来代替抽象?
【发布时间】:2021-03-12 04:20:57
【问题描述】:

我正在我的 flutterfire 项目中准备一个类,我想使用一些无法进一步更改的方法,以便我想知道 Dart 中 static 关键字的概念?

【问题讨论】:

    标签: flutter class dart static static-methods


    【解决方案1】:

    “静态”表示成员在类本身而不是类的实例上可用。这就是它的全部含义,它不用于其他任何事情。 static 修改成员

    静态方法 静态方法(类方法)不对实例进行操作,因此无权访问它。但是,它们确实可以访问静态变量。

    void main() {
    
     print(Car.numberOfWheels); //here we use a static variable.
    
    //   print(Car.name);  // this gives an error we can not access this property without creating  an instance of Car class.
    
      print(Car.startCar());//here we use a static method.
    
      Car car = Car();
      car.name = 'Honda';
      print(car.name);
    }
    
    class Car{
    static const numberOfWheels =4;
      Car({this.name});
      String name;
      
    //   Static method
      static startCar(){
        return 'Car is starting';
      }
      
    }
    

    【讨论】:

      【解决方案2】:

      dart 中的 static 关键字用于声明仅属于类而不是瞬间的变量或方法,这意味着该类只有该变量或方法的一个副本以及那些静态变量(类变量)或静态方法(类方法) ) 不能被类创建的实例使用。

      例如,如果我们将一个类声明为

          class Foo {
      
      static String staticVariable = "Class variable";
      final String instanceVariable = "Instance variable";
      
      static void staticMethod(){
        print('This is static method');
      }
      
      void instanceMethod(){
        print('instance method');
      }
      }`
      

      这里要记住的是静态变量只创建一次,并且类创建的每个实例都有不同的实例变量。因此,您不能从类实例中调用静态变量。 以下代码有效,

      Foo.staticVariable; 
      Foo().instanceVariable;
      Foo.staticMethod();
      Foo().instanceMethod();
      

      下面的代码会报错

      Foo().staticVariable;
      Foo.instanceVariable;
      Foo().staticMethod;
      Foo.instanceMethod
      

      静态变量和方法的使用

      当您具有与类相关的常量值或公共值时,您可以使用静态变量。

      您可以在此处阅读更多信息 - https://dart.dev/guides/language/language-tour#class-variables-and-methods

      【讨论】:

        猜你喜欢
        • 2020-03-24
        • 1970-01-01
        • 1970-01-01
        • 2011-10-30
        • 2012-07-24
        • 2011-11-11
        • 2010-11-05
        • 2010-12-06
        • 2012-01-16
        相关资源
        最近更新 更多