简体   繁体   中英

What does it mean when a Type name is “_Closure$__1”?

I have a method that I'm using to output all the class names in an Assembly:

private static void ListClasses()
{
    var assembly = Assembly.LoadFile(@"path\to\my.dll");
    Type[] types = assembly.GetTypes().Where(t => t.IsClass).ToArray();

    using (StreamWriter w = File.AppendText("log.txt"))
    {
        foreach (var type in types)
        {
            w.WriteLine(type.Namespace + "," + type.Name);
            w.Flush();
        }

        w.Close();
    }

    Console.WriteLine("Done");
}

The only problem I'm seeing is some of the class names have this output:

The.Namespace,_Closure$__1

The last number will increment each time the Type name needs to be output this way. Can anyone shed some light as to what this means?

Those are compiler generated classes used by lambda expressions to capture free variables in the lambda expression.

http://msdn.microsoft.com/en-us/library/bb981314%28v=vs.80%29.aspx

A closure is when a local variable is persisted beyond its scope. For example:

public IEnumerable<Employee> GetEmployees(string lastName)
{
    return employees.Where(e => e.LastName == lastName);
}

Compiling this will result in closure, where the lastName will keep its value behind the scenes until the Where is evaluated.

For more information: http://en.wikipedia.org/wiki/Closure_(computer_science )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM