Skip to content

Instantly share code, notes, and snippets.

@paralleltree
Created September 21, 2014 09:35
Show Gist options
  • Save paralleltree/c41c82c62a14b3d5ffb9 to your computer and use it in GitHub Desktop.
Save paralleltree/c41c82c62a14b3d5ffb9 to your computer and use it in GitHub Desktop.
遅延実行で嵌った罠。いちいち新しいインスタンスが作成されてしまう。
using System;
using System.Collections.Generic;
using System.Linq;
static class Program
{
static void Main(string[] args)
{
string[] inner = new string[] { "a", "b", "c", "d", "e" };
string[] outer = new string[] { "b", "d" };
var linked = outer.Join(inner, p => p, q => q, (p, q) => new Foo(p));
foreach (var item in linked)
{
item.Increment();
Console.WriteLine("Name: {0}, Counter: {1}", item.Name, item.Counter);
}
foreach (var item in linked)
{
item.Increment();
Console.WriteLine("Name: {0}, Counter: {1}", item.Name, item.Counter);
}
}
class Foo
{
public int Counter { get; private set; }
public string Name { get; private set; }
public Foo(string name)
{
this.Counter = 0;
this.Name = name;
}
public void Increment()
{
Counter++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment