What is this Type in .NET (Reflection)

后端 未结 2 1721
鱼传尺愫
鱼传尺愫 2020-12-29 20:11

What is this Type in .NET? I am using reflection to get a list of all the classes and this one turns up.

What is it? where does it come from? How is the name Display

2条回答
  •  死守一世寂寞
    2020-12-29 20:24

    It's almost certainly a class generated by the compiler due to a lambda expression or anonymous method. For example, consider this code:

    using System;
    
    class Test
    {
        static void Main()
        {
            int x = 10;
            Func foo = y => y + x;
            Console.WriteLine(foo(x));
        }
    }
    

    That gets compiled into:

    using System;
    
    class Test
    {
        static void Main()
        {
            ExtraClass extra = new ExtraClass();
            extra.x = 10;
    
            Func foo = extra.DelegateMethod;
            Console.WriteLine(foo(x));
        }
    
        private class ExtraClass
        {
            public int x;
    
            public int DelegateMethod(int y)
            {
                return y + x;
            }
        }
    }
    

    ... except using <>c_displayClass1 as the name instead of ExtraClass. This is an unspeakable name in that it isn't valid C# - which means the C# compiler knows for sure that it won't appear in your own code and clash with its choice.

    The exact manner of compiling anonymous functions is implementation-specific, of course - as is the choice of name for the extra class.

    The compiler also generates extra classes for iterator blocks and (in C# 5) async methods and delegates.

提交回复
热议问题