다음을 통해 공유


CodeDomProvider.GenerateCodeFromMember 메서드

정의

지정된 CodeDOM(코드 문서 개체 모델) 멤버 선언에 대한 코드를 생성한 다음 지정된 옵션을 사용하여 지정된 텍스트 작성기에 해당 코드를 보냅니다.

public:
 virtual void GenerateCodeFromMember(System::CodeDom::CodeTypeMember ^ member, System::IO::TextWriter ^ writer, System::CodeDom::Compiler::CodeGeneratorOptions ^ options);
public virtual void GenerateCodeFromMember (System.CodeDom.CodeTypeMember member, System.IO.TextWriter writer, System.CodeDom.Compiler.CodeGeneratorOptions options);
abstract member GenerateCodeFromMember : System.CodeDom.CodeTypeMember * System.IO.TextWriter * System.CodeDom.Compiler.CodeGeneratorOptions -> unit
override this.GenerateCodeFromMember : System.CodeDom.CodeTypeMember * System.IO.TextWriter * System.CodeDom.Compiler.CodeGeneratorOptions -> unit
Public Overridable Sub GenerateCodeFromMember (member As CodeTypeMember, writer As TextWriter, options As CodeGeneratorOptions)

매개 변수

member
CodeTypeMember

코드를 생성할 멤버를 나타내는 CodeTypeMember 개체입니다.

writer
TextWriter

출력 코드가 전달될 TextWriter입니다.

options
CodeGeneratorOptions

코드를 생성하기 위해 사용할 옵션을 나타내는 CodeGeneratorOptions입니다.

예외

이 메서드가 파생 클래스에서 재정의되지 않은 경우

예제

다음 코드 예제에서는 사용 GenerateCodeFromMember 하는 방법을 보여 줍니다는 및 클래스에 의해 CSharpCodeProviderVBCodeProvider 구현 된 메서드입니다.

using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.IO;
using System.Text.RegularExpressions;

namespace BasicCodeDomApp
{
    class Program
    {
        static string providerName = "cs";
        static string sourceFileName = "test.cs";
        static CodeSnippetTypeMember snippetMethod;
        static void Main(string[] args)
        {
            CodeDomProvider provider = CodeDomProvider.CreateProvider(providerName);

            // Create a code snippet to be used in the graph.
            GenCodeFromMember(provider, new CodeGeneratorOptions());

            LogMessage("Building CodeDOM graph...");

            CodeCompileUnit cu = new CodeCompileUnit();

            cu = BuildClass1();

            StringWriter sw = new StringWriter();

            LogMessage("Generating code...");
            provider.GenerateCodeFromCompileUnit(cu, sw, null);

            string output = sw.ToString();

            LogMessage("Dumping source...");
            LogMessage(output);

            LogMessage("Writing source to file...");
            Stream s = File.Open(sourceFileName, FileMode.Create);
            StreamWriter t = new StreamWriter(s);
            t.Write(output);
            t.Close();
            s.Close();

            CompilerParameters opt = new CompilerParameters(new string[]{
                                      "System.dll" });
            opt.GenerateExecutable = false;
            opt.OutputAssembly = "Sample.dll";

            CompilerResults results;

            LogMessage("Compiling with " + providerName);
            results = provider.CompileAssemblyFromFile(opt, sourceFileName);

            OutputResults(results);
            if (results.NativeCompilerReturnValue != 0)
            {
                LogMessage("");
                LogMessage("Compilation failed.");
            }
            else
            {
                LogMessage("");
                LogMessage("Demo completed successfully.");
            }
            File.Delete(sourceFileName);
        }

        // Build a library program graph using
        // System.CodeDom types.
        public static CodeCompileUnit BuildClass1()
        {
            // Create a new CodeCompileUnit to contain
            // the program graph.
            CodeCompileUnit compileUnit = new CodeCompileUnit();

            // Declare a new namespace called Samples.
            CodeNamespace samples = new CodeNamespace("Samples");
            // Add the new namespace to the compile unit.
            compileUnit.Namespaces.Add(samples);

            // Add the new namespace import for the System namespace.
            samples.Imports.Add(new CodeNamespaceImport("System"));

            // Declare a new type called Class1.
            CodeTypeDeclaration class1 = new CodeTypeDeclaration("Class1");

            // Add the new type to the namespace type collection.
            samples.Types.Add(class1);

            class1.Members.Add(snippetMethod);

            return compileUnit;
        }
        static void LogMessage(string text)
        {
            Console.WriteLine(text);
        }

        static void OutputResults(CompilerResults results)
        {
            LogMessage("NativeCompilerReturnValue=" +
                results.NativeCompilerReturnValue.ToString());
            foreach (string s in results.Output)
            {
                LogMessage(s);
            }
        }
        static void GenCodeFromMember(CodeDomProvider provider, CodeGeneratorOptions options)
        {
            options.BracingStyle = "C";
            CodeMemberMethod method1 = new CodeMemberMethod();
            method1.Name = "ReturnString";
            method1.Attributes = MemberAttributes.Public;
            method1.ReturnType = new CodeTypeReference("System.String");
            method1.Parameters.Add(new CodeParameterDeclarationExpression("System.String", "text"));
            method1.Statements.Add(new CodeMethodReturnStatement(new CodeArgumentReferenceExpression("text")));
            StringWriter sw = new StringWriter();
            provider.GenerateCodeFromMember(method1, sw, options);
            snippetMethod = new CodeSnippetTypeMember(sw.ToString());
        }
    }
}
Imports System.CodeDom
Imports System.CodeDom.Compiler
Imports System.IO
Imports System.Text.RegularExpressions



Class Program
    Private Shared providerName As String = "vb"
    Private Shared sourceFileName As String = "test.vb"
    Private Shared snippetMethod As CodeSnippetTypeMember
    
    Shared Sub Main(ByVal args() As String) 
        Dim provider As CodeDomProvider = CodeDomProvider.CreateProvider(providerName)
        
        ' Create a code snippet to be used in the graph.
        GenCodeFromMember(provider, New CodeGeneratorOptions())
        
        LogMessage("Building CodeDOM graph...")
        
        Dim cu As New CodeCompileUnit()
        
        cu = BuildClass1()
        
        Dim sw As New StringWriter()
        
        LogMessage("Generating code...")
        provider.GenerateCodeFromCompileUnit(cu, sw, Nothing)
        
        Dim output As String = sw.ToString()
        
        LogMessage("Dumping source...")
        LogMessage(output)
        
        LogMessage("Writing source to file...")
        Dim s As Stream = File.Open(sourceFileName, FileMode.Create)
        Dim t As New StreamWriter(s)
        t.Write(output)
        t.Close()
        s.Close()
        
        Dim opt As New CompilerParameters(New String() {"System.dll"})
        opt.GenerateExecutable = False
        opt.OutputAssembly = "Sample.dll"
        
        Dim results As CompilerResults
        
        LogMessage(("Compiling with " + providerName))
        results = provider.CompileAssemblyFromFile(opt, sourceFileName)
        
        OutputResults(results)
        If results.NativeCompilerReturnValue <> 0 Then
            LogMessage("")
            LogMessage("Compilation failed.")
        Else
            LogMessage("")
            LogMessage("Demo completed successfully.")
        End If
        File.Delete(sourceFileName)
    
    End Sub
    
    
    ' Build a library program graph using 
    ' System.CodeDom types.
    Public Shared Function BuildClass1() As CodeCompileUnit 
        ' Create a new CodeCompileUnit to contain 
        ' the program graph.
        Dim compileUnit As New CodeCompileUnit()
        
        ' Declare a new namespace called Samples.
        Dim samples As New CodeNamespace("Samples")
        ' Add the new namespace to the compile unit.
        compileUnit.Namespaces.Add(samples)
        
        ' Add the new namespace import for the System namespace.
        samples.Imports.Add(New CodeNamespaceImport("System"))
        
        ' Declare a new type called Class1.
        Dim class1 As New CodeTypeDeclaration("Class1")
        
        ' Add the new type to the namespace type collection.
        samples.Types.Add(class1)
        
        class1.Members.Add(snippetMethod)
        
        Return compileUnit
    
    End Function 'BuildClass1
    
    Shared Sub LogMessage(ByVal [text] As String) 
        Console.WriteLine([text])
    
    End Sub
    
    
    Shared Sub OutputResults(ByVal results As CompilerResults) 
        LogMessage(("NativeCompilerReturnValue=" + results.NativeCompilerReturnValue.ToString()))
        Dim s As String
        For Each s In  results.Output
            LogMessage(s)
        Next s
    
    End Sub
    
    Shared Sub GenCodeFromMember(ByVal provider As CodeDomProvider, ByVal options As CodeGeneratorOptions) 
        options.BracingStyle = "C"
        Dim method1 As New CodeMemberMethod()
        method1.Name = "ReturnString"
        method1.Attributes = MemberAttributes.Public
        method1.ReturnType = New CodeTypeReference("System.String")
        method1.Parameters.Add(New CodeParameterDeclarationExpression("System.String", "text"))
        method1.Statements.Add(New CodeMethodReturnStatement(New CodeArgumentReferenceExpression("text")))
        Dim sw As New StringWriter()
        provider.GenerateCodeFromMember(method1, sw, options)
        snippetMethod = New CodeSnippetTypeMember(sw.ToString())
    
    End Sub
End Class

설명

기본 클래스 구현은 을 NotImplementedExceptionthrow합니다. 이 메서드의 구현을 설명하는 설명서는 를 참조하세요 CSharpCodeProvider.GenerateCodeFromMember .

적용 대상

추가 정보