". Net deep Breathing" detail CodeDom (4): type definition

Source: Internet
Author: User

In the previous article, you said the namespace, and guess what to say next. Yes, the namespace below is the type, knowing how to generate the namespace definition code, and then learn how to declare the type.

There are typically several types of CLR: classes, interfaces, structs, enumerations, delegates. There are so many, it should not have been missed out of it.

Defines a type that can be completed with the CodeTypeDeclaration class in addition to the delegate. The CodeNamespace class exposes a types collection, and the defined type must be added to the collection to be associated with the namespace.

As an example, the following code defines a class called Mouse.

            //Compilation UnitCodeCompileUnit unit =NewCodeCompileUnit (); //name SpaceCodeNamespace Nspace =NewCodeNamespace (); Nspace. Name="Sample"; Unit.            Namespaces.add (Nspace); //class declarationCodeTypeDeclaration CLSDCL =NewCodeTypeDeclaration (); CLSDCL. Name="Mouse"; //public and sealed, not allowed to inheritCLSDCL. TypeAttributes = System.Reflection.TypeAttributes.Sealed |System.Reflection.TypeAttributes.Public; //in the Join type collectionNspace.            Types.add (CLSDCL); CodeDomProvider PRD= Codedomprovider.createprovider ("CS"); Prd. Generatecodefromcompileunit (unit, Console.Out,NULL);

It is not necessary to explicitly say isclass to true, because the default is to generate classes (class). Here's a little old week to explain.

The accessibility of the description type has two properties, one is inherited from the CodeTypeMember class Attributes, because the MemberAttributes enumeration cannot be combined (I want to define the class as public sealed), So I chose the typeattributes, which used the value is the reflection inside the TypeAttributes enumeration, this enumeration can be used in combination of multiple values.

The generated code is as shown.

The following code defines a structure named point.

            New CodeTypeDeclaration ("point");             true ;             = System.Reflection.TypeAttributes.NotPublic;            Nspace. Types.add (STRDCL);

Notpublic indicates that the type accessibility is internal, that is, only the current assembly is visible. Generate the code as shown in.

Once you know how to define classes and structs, it's hard for you to enumerate.

            New CodeTypeDeclaration ("AccessType");             true ;            Nspace. Types.add (ENDCL);

The generated code is as follows.

But, the big friends will certainly ask, that commission. The CodeTypeDeclaration class cannot be used to declare a delegate type, but it derives a codetypedelegate class that defines the delegate type.

We know that a delegate is similar to a method, so you think that a delegate type requires several elements. First, the list of arguments. Then, you have to have a return value. Good, or the actual effect is useful, not much to say, to, first define a delegate type test hackers.

CodeCompileUnit unit =NewCodeCompileUnit (); CodeNamespace NS=NewCodeNamespace ("Calculators"); Unit.            Namespaces.add (NS); Codetypedelegate DL=NewCodetypedelegate ("Onadd"); //The return value is of type intDl. ReturnType =NewCodeTypeReference (typeof(int)); //two parameterscodeparameterdeclarationexpression P1 =Newcodeparameterdeclarationexpression (); P1. Name="x"; P1. Type=NewCodeTypeReference (typeof(int)); codeparameterdeclarationexpression P2=Newcodeparameterdeclarationexpression (); P2. Name="y"; P2. Type=NewCodeTypeReference (typeof(int)); Dl.            Parameters.Add (p1); Dl.            Parameters.Add (p2); Ns. Types.add (DL);

CodeTypeReference is used to generate type reference code, you can provide type information with a type object, or it can be supplied with a string. Method parameters can be declared with the Codeparameterdeclarationexpression class, with the core element being the parameter type and the argument name.

If the delegate has no arguments, there is no need to add anything to the Parameters collection, with several parameters added.

The last generated delegate type code is as follows.

The following code generates a delegate type that has no parameters and returns void.

            New Codetypedelegate ("DoWork");             New CodeTypeReference (typeof(void));            Ns. Types.add (DL2);

The generated delegate type is

============================================

At this point, you might think that there are inheritance relationships between types, such as classes and classes, where classes/structs can implement interfaces.

The following code declares two classes--a, B, where B derives from A.

CodeCompileUnit unit =NewCodeCompileUnit (); CodeNamespace NS=NewCodeNamespace ("Samples"); Unit.            Namespaces.add (NS); CodeTypeDeclaration T1=NewCodeTypeDeclaration ("A"); CodeTypeDeclaration T2=NewCodeTypeDeclaration ("B"); //B derives from AT2. Basetypes.add (Newcodetypereference (t1.            Name)); Ns. Types.addrange (NewCodetypedeclaration[] {t1, t2});

The CodeTypeDeclaration class has a BaseTypes collection that is used to set the base class for that type.

Here you have a question: Although BaseTypes is a collection, you can add n type references, but you have to obey them. NET object-oriented rules, that is, a class cannot inherit more, but a type can implement multiple interfaces.

Although you can do this:

            T2. Basetypes.add (new  codetypereference (t1. Name));            T2. Basetypes.add (new codetypereference (typeof(string)));

This code is then generated.

However, you will have to think about it, such code can be compiled, not interested friends may wish to try.

Want to try it, good, the old week on caught dead, yours faithfully crossing mock not a.

CodeDomProvider PRD = Codedomprovider.createprovider ("C #"); //Generate CodePrd. Generatecodefromcompileunit (unit, Console.Out,NULL); CompilerParameters Options=NewCompilerParameters (); //Output FileOptions. outputassembly ="Test.dll"; //Referenced assembliesOptions. Referencedassemblies.add ("System.dll"); //Start compilingCompilerResults res =prd.compileassemblyfromdom (options, unit); //200% Error            if(Res. Errors.Count = =0) {Console.WriteLine ("The compilation is complete. "); Console.WriteLine ($"Output assembly: {res.CompiledAssembly.Location}"); }            Else            {                foreach(CompilerError ERinchRes. Errors) {Console.WriteLine ($"{er. ErrorNumber}-{er. ErrorText}"); }            }

Then, a compilation, there is a fun to see.

This tells you that the base class of Class A cannot have more than one class.

Let's look at how to implement multiple interfaces.

CodeCompileUnit unit =NewCodeCompileUnit (); CodeNamespace NS=NewCodeNamespace ("Commons"); Unit.            Namespaces.add (NS); //These are both interfaces.CodeTypeDeclaration T1 =NewCodeTypeDeclaration ("IBall"); T1. Isinterface=true; CodeTypeDeclaration T2=NewCodeTypeDeclaration ("IPlayer"); T2. Isinterface=true; Ns.            Types.add (t1); Ns.            Types.add (T2); //This is the class that implements the above two interfacescodetypedeclaration t3 =NewCodeTypeDeclaration ("Footballplayer"); T3. Basetypes.add (Newcodetypereference (t1.            Name)); T3. Basetypes.add (Newcodetypereference (T2.            Name)); Ns. Types.add (T3);

Both T1 and T2 are interface types, and T3 is a class that implements the first two interfaces. After running, the following code is generated.

OK, so much for the type definition today. Along this level, the next article, the old week will talk about the definition of type members.

Dinner is over.

". Net deep Breathing" detail CodeDom (4): type definition

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.