Шаг 119 - Добавляем класс в пространство имен CODEDom

Итак, наша задача добавить класс.

using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.IO;

class MainClass
{
	public static void Main(string[] args)
	{
		CodeCompileUnit compileunit = new CodeCompileUnit();
		CodeNamespace Samples = new CodeNamespace("Samples");
		CSharpCodeProvider cs = new CSharpCodeProvider();
		CodeGeneratorOptions go = new CodeGeneratorOptions();
		ICodeGenerator  ic= cs.CreateGenerator();
		
		CodeTypeDeclaration Class1 = new CodeTypeDeclaration("MyClass1");
		CodeTypeDeclaration Class2 = new CodeTypeDeclaration("MyClass2");
		Samples.Types.Add(Class1);
		Samples.Types.Add(Class2);
		
		Stream ss=File.OpenWrite("d:\\test.txt");
		StreamWriter s = new StreamWriter(ss);
		compileunit.Namespaces.Add(Samples);
		ic.GenerateCodeFromCompileUnit(compileunit,s,go);
		s.Close();
		ss.Close();
	}
}

Класс CodeTypeDeclaration используется для объявления новых структур или классов. После этого мы можем добавить объект к нашему рабочему пространству Samples.Types.Add.

Вот такой будет результат.


//------------------------------------------------------------------------------
// <autogenerated>
//     This code was generated by a tool.
//     Runtime Version: 1.0.2914.16
//
//     Changes to this file may cause incorrect behavior and will be lost if 
//     the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------


namespace Samples {

    public class MyClass1 {
    }
    
    public class MyClass2 {
    }
}

Загрузить проект | Предыдущий Шаг | Следующий Шаг | Оглавление
Автор Каев Артем - 18.10.2001