pondělí 1. listopadu 2010

Closures and properties -> problems

OK. So C# has lambdas and closures. Fine. You've got to be carefull though! I have not tested all options, but one thing I know for sure already. It's unable to close over an object whose property I access. So if you have something like

foreach (var column in tracked.TrackedColumns) {
 if (column.Type.Contains("char")) {
  column.AsChar = (t => "'\"'+" + (t.Contains("[") ? t + column.Name + "]" : t + ".[" + column.Name + "]") + "+'\"'");
 } else if (column.Type.Contains("date")) {
  column.AsChar = (t => "'\"'" + (t.Contains("[") ? HistoryDatetimeFormat(t + column.Name + "]") : HistoryDatetimeFormat(t + ".[" + column.Name + "]")));
 } else if ...

you will find out that this doesn't work. It'll behave as if all the objects in the collection had the same function, and you end up with the column name of the first one. You have to copy the column name into a local variable. 

foreach (var column in tracked.TrackedColumns) {
 string name = column.Name;
 if (column.Type.Contains("char")) {
  column.AsChar = (t => "'\"'+" + (t.Contains("[") ? t + name + "]" : t + ".[" + name + "]") + "+'\"'");
 } else if (column.Type.Contains("date")) {
  column.AsChar = (t => "'\"'" + (t.Contains("[") ? HistoryDatetimeFormat(t + name + "]") : HistoryDatetimeFormat(t + ".[" + name + "]")));
 } else if 

Žádné komentáře:

Okomentovat