是否可以安全解构,例如带有命名变量?

问题描述 投票:0回答:1

我喜欢使用

records
,最近我开始享受直接将记录解构为属性,单行代码看起来非常好:

(instanceA.Property, instanceB.Property1, instanceB.Property2) = SomeMethodReturningRecord(...);

但是,我担心未来的重构,记录成员可能会重新排序,并且如果属性属于同一类型,那么这样的代码很容易出现错误。

命名参数,它解决了排序问题并有助于使方法重构安全。

有类似解构的东西吗?


映射名称会很酷,例如(伪代码):

(a:instanceA.Property, b:instanceB.Property1, c:instanceB.Property2) = SomeMethodReturningRecordBla(...);
...
public record Bla(double a, double b, double c);
c# deconstructor
1个回答
0
投票

是的,您可以按照以下方式操作:

public record Money(decimal Value, string Currency);
Money myMoney = new(42, "USD");

(decimal moneyValue, string currency) = myMoney;
© www.soinside.com 2019 - 2024. All rights reserved.