CodeDom - Linking multiple classes within a single

2019-08-31 02:51发布

问题:

I have a C# application that I am trying to re-create through the use of CodeDom. This application has four classes inside of it. If I were to go into this applications directory, I would find the project file (App.csproj), and if I were to start this project file, all four classes would load together. Furthermore, if I were to build this application, all four classes would build together.

My Question: How on earth can I create this functionality through the use of CodeDom?

I have sucessfully created one of the four classes using CodeDom, but how can I go about creating the next three classes (and linking them) to the first class that I already created?

I know this may sound confusing but I will explain more if necessary.

回答1:

If the classes are in the same namespace you can add them all to one CodeNamespace object and generate the code from that.

If there in different namespaces you can add the namespace of the other Classes to your first class by adding the namespaces reference of the other class's to the namespace object you are working in:-

// Add the Namespace of the other class to the current namespace onject defaultNameSpace.Imports.Add(new CodeNamespaceImport("Project.Namespace.Namespace"));

Where defaultNameSpace is a type of CodeNamespace. The first Class you have built is added to this CodeNamespace object as below and then the code is generated from that :-

defaultNameSpace.Types.Add(mainClass);

mainClass being a type of CodeTypeDeclaration.

Hope this helps.