如何使用“with”关键字添加?
c#
c#-9.0
public record Cube(int x, int y, int z, int w);
我最近遇到了我这样做的时间:
var next = new Cube(existing.x + 1, existing.y, existing.z, existing.w);
我认为必须有一种更简洁的方法来向记录添加任意值。但是当我尝试这个时:
var next = existing with { x = x+1 };
它哭是因为您无权访问要添加的值。相反,我必须这样做:
var next = existing with { x = existing.x+1 };
我只是想从with关键字中获得太多吗?
回答
我对 with 语法的理解正是这样 - 您必须在 width 语句的左侧引用对象的名称。这似乎与此处的规范一致:https : //docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/records
虽然x = x + 1很方便,但它在 x 来自何处的来源上并没有很好的表现力。