English 中文(简体)
我无法改变关闭时的变数, 为什么?
原标题:I cannot modify a variable from a closure, why?

我想看看我是否能用时装写出C#代码, 但我有出乎意料的行为。我知道C#没有被打破, 但我不明白什么是错的,为什么它不做我认为应该做的事。

< 强度 > Code :

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

为什么第一个名字没有改变?

最佳回答

fullName 没有。 它在 CreatePerson 中计算,并存储为 string , 而不是以后对字符串进行评价的属性。

您可以像对 SetFirstName 所做的那样,用羊羔来造成延迟评价。

问题回答

It gives you fist assignment of FullName.
You need to re-assign FullName

FullName = string.Format("{0} {1}", firstName, lastName)

SetFirstName 函数上的 SetFirstName 函数





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签