What is metadata in .NET?

后端 未结 6 1623

I googled several sites to understand what metadata is in .NET and it means.

I\'m still new to C# WPF desktop application programming. Back when I was

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-23 00:17

    Metadata is parts of the information from the source code itself which is stored in a special section in the assembly when compiled. It is really an implementation detail in how assemblies are structured. For typical C# application development you don't really need to know about this. It is mostly relevant if you develop developer tools.

    The term "metadata" is somewhat misleading. Assembly metadata includes stuff from the code like constants and string literals which is not really metadata in the usual sense of the word. A more correct term would perhaps be non-executable data.

    When C# is compiled into an assembly, the compilation output is separated into two sections. The IL which is the actual executable code in bytecode format, and the "metadata" which is all the other stuff: type, interface, and member declarations, method signatures, constants, external dependencies and so on.

    Take this program:

    class Program
    {
        public static void Main(string[] args)
        {
            var x = 2 + 2;
            Console.WriteLine("Hello World!");
        }
    }
    

    When this program is compiled into an assembly, it is separated into metadata and IL. The metadata contains these declarations (represented in a language-independent binary format):

    class Program
    {
        public static void Main(string[] args);
    }
    

    Furthermore metadata contains the string literal "Hello World!", and the information that the assembly references System.Console.WriteLine in mscorlib.dll.

    Only this part gets compiled into IL:

    var x = 2 + 2;
    Console.WriteLine("Hello World!");
    

    With the caveat that the method reference and the literal string are represented in the IL as pointers into the metadata. On the other hand the method declarations in the metadata have pointers into the IL to the code which implement the method body.

    So it comes down to a way to separate the executable (imperative) IL code from the non-executable (declarative) parts.

    Why is this separation useful? Because it allows tools to extract and use the metadata without having to actually execute any of the IL. For example Visual Studio is able to provide code completion to members defined in an assembly just by reading the metadata. The compiler can check that methods called from other assemblies actually exists and parameters match and so on.

提交回复
热议问题