我想看看我是否可以以 javascript-fashion 的方式编写一些 c# 代码,但我得到了一个意想不到的行为。我知道 c# 没有坏,但我不明白什么是错的,为什么它没有做我认为应该做的事情。
代码:
class Program
{
static void Main(string[] args)
{
var person = CreatePerson(new{
FirstName = "Lucas",
LastName = "Ontivero",
Age = 34
});
Console.WriteLine("Name....... : {0}", person.FullName);
Console.WriteLine("IsJuvenile. : {0}", person.IsJuvenile);
person.SetFirstName("Pablo");
Console.WriteLine("Name....... : {0}", person.FullName);
Console.ReadKey();
}
static private dynamic CreatePerson(dynamic cfg)
{
string firstName = cfg.FirstName;
string lastName = cfg.LastName;
var age = cfg.Age;
return new{
FullName = string.Format("{0} {1}", firstName, lastName),
FirstName = firstName,
LastName = lastName,
SetFirstName = new Action<string>(fn => firstName= fn),
SetLastName = new Action<string>(ln => lastName = ln),
IsJuvenile = age < 18
};
}
}
输出:
Name....... : Lucas Ontivero
IsJuvenile. : False
Name....... : Lucas Ontivero
但我期望:
Name....... : Lucas Ontivero
IsJuvenile. : False
Name....... : Pablo Ontivero
为什么名字不会改变?