【发布时间】:2020-10-18 18:08:47
【问题描述】:
在尝试使用 C# 9 记录时,我遇到了一个相当奇怪的行为。我的记录是这样的:
record MyRecord(Func<MyRecord> SomeAction, string Name)
{
public MyRecord(string name) : this(null, name)
{
SomeAction = Foo;
}
// Foo returns 'this' with SomeAction changed to Bar
MyRecord Foo()
{
Console.WriteLine("Foo: " + SomeAction.Method.Name);
return this with { SomeAction = Bar };
}
MyRecord Bar()
{
Console.WriteLine("Bar: " + SomeAction.Method.Name);
return this;
}
}
我是这样使用它的:
class Program
{
static void Main(string[] args)
{
var r = new MyRecord("Foo");
Console.WriteLine(r.ToString());
r = r.SomeAction();
r = r.SomeAction();
r = r.SomeAction();
}
}
我期望的输出是
Foo: Foo
Bar: Bar
Bar: Bar
但是,我得到的实际输出:
Foo: Foo
Bar: Foo
Foo: Foo
这是一个错误还是我遗漏了什么?
【问题讨论】: