英文:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论