Is object initializer avalible in flutter (dart) like java or c# in the spirit of the following code?

huangapple go评论63阅读模式
英文:

Is object initializer avalible in flutter (dart) like java or c# in the spirit of the following code?

问题

在Flutter (Dart) 中是否有类似于 Java 或 C# 中对象初始化器的功能?以下是类似于您提供的代码示例的一种方式:

Person p = Person(
  firstName: 'John',
  lastName: 'Doe',
  address: Address(
    street: '1234 St.',
    city: 'Phoenix',
  ),
);
英文:

Is object initializer avalible in flutter (dart) like java or c# in the spirit of the following code?

Person p = new Person()
{
    FirstName = "John",
    LastName = "Doe",
    Address = new Address()
    {
        Street = "1234 St.",
        City = "Phoenix"
    }
};

答案1

得分: 1

为了在Dart中实现相同的效果,请在构造函数中使用命名参数。例如:

class Person {
  Person({ this.firstName, this.lastName, this.address, this.tn });

  String firstName;
  String lastName;
  String tn;
  Address address;
}

class Address {
  Address({ this.street, this.city, this.zip });
 
  String street;
  String city;
  String zip;
}

现在,您可以通过使用命名参数来初始化这些类中的一些或所有字段,只需提供所需的参数和值,而且顺序可以任意。例如:

// 创建一个没有初始化字段的人
var person = Person(); 

// 只初始化姓和名
var person1 = Person(firstName: 'John', lastName: 'Doe'); 

// 这相当于原问题中的情况
var person2 = Person(address: Address(street: '1234 St.', city: 'Phoenix'), 
  lastName: 'Doe', firstName: 'John');
英文:

To get the same effect in Dart, use named parameters in the constructor. For example:

class Person {
  Person({ this.firstName, this.lastName, this.address, this.tn });

  String firstName;
  String lastName;
  String tn;
  Address address;
}

class Address {
  Address({ this.street, this.city, this.zip });
 
  String street;
  String city;
  String zip;
}

Now you could initialize some or all of the fields in these classes by using the named parameters - just providing only the argument and values you need, and in any order. For example:

// create a person with no fields initialized
var person = Person(); 

// only init first and last
var person1 = Person(firstName: 'John', lastName: 'Doe'); 

// this is equivalent to the OPs question
var person2 = Person(address: Address(street: '1234 St.', city: 'Phoenix'), 
  lastName: 'Doe', firstName: 'John');

</details>



huangapple
  • 本文由 发表于 2020年8月29日 19:07:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63646266.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定