使用 Kotlin 时,可以使用apply设置现有对象的多个属性并保持代码更清晰,例如,而不是:
person.firstName = "John"
person.lastName = "Doe"
person.phone = "123 456 789"
Run Code Online (Sandbox Code Playgroud)
我们可以用:
person.apply {
firstName = "John"
lastName = "Doe"
phone = "123 456 789"
}
Run Code Online (Sandbox Code Playgroud)
是否有与applyC# 中的等效项?
最接近的是,using但据我所知,它不能以这种方式使用。
编辑:我知道C# 中的对象初始值设定项,但实际上我正在寻找可以为现有对象(例如从数据库中获取的对象)完成的操作。
小智 5
试试这个.... https://dev.to/amay077/kotlins-scope-functions-in-c-pbn
为方便起见,下面粘贴了代码,但上面的链接是源...
static class ObjectExtensions
{
// Kotlin: fun <T, R> T.let(block: (T) -> R): R
public static R Let<T, R>(this T self, Func<T, R> block)
{
return block(self);
}
// Kotlin: fun <T> T.also(block: (T) -> Unit): T
public static T Also<T>(this T self, Action<T> block)
{
block(self);
return self;
}
}
Run Code Online (Sandbox Code Playgroud)
可以这样使用......
var model = new MyModel().Also(m => {
m.Initialize();
m.Load(path);
});
Run Code Online (Sandbox Code Playgroud)
您可以通过对象初始值设定项以这种方式使用它:
var person = new Person
{
FirstName = "John",
LastName = "Doe",
Phone = "123 456 789"
};
Run Code Online (Sandbox Code Playgroud)
或者使用构造函数:
var person = new Person("John", "Doe", "123 456 789");
Run Code Online (Sandbox Code Playgroud)
对于构造函数选项,您的类必须如下所示:
class Person
{
public Person(string firstName, string lastName, string phone)
{
FirstName = firstName;
LastName = lastName;
Phone = phone;
}
public string FirstName { get;set; }
public string LastName { get;set; }
public string Phone { get;set; }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1078 次 |
| 最近记录: |