使用C#中的CodeDOM为变量赋值

时间:2016-02-19 09:59:45

标签: c# codedom

我使用CodeDOM生成C#代码,但我无法为后续的语句行生成代码。

string FileName=String.Empty;
FileName=Path.GetFileName(file1);

从上面的代码我已经使用以下代码段

编写了第一行的代码
using(CodeVariableDeclarationStatement strFileName = 
    new CodeVariableDeclarationStatement(typeof(string), "strFileName",
    new CodeTypeReferenceExpression("String.Empty"));) 

但无法使用codeDOM为第二行添加代码。所以,请让我知道如何实现它。

1 个答案:

答案 0 :(得分:2)

// For the first line: string FileName = string.Empty;
var declareVariableFileName = new CodeVariableDeclarationStatement(                 // Declaring a variable.
    typeof(string),                                                                 // Type of variable to declare.
    "FileName",                                                                     // Name for the new variable.
    new CodePropertyReferenceExpression(                                            // Initialising with a property.
        new CodeTypeReferenceExpression(typeof(string)), "Empty"));                 // Identifying the property to invoke.

// For the second line: FileName = System.IO.Path.GetFileName(file1);
var assignGetFileName = new CodeAssignStatement(                                    // Assigning a value to a variable.
    new CodeVariableReferenceExpression("FileName"),                                // Identifying the variable to assign to.
    new CodeMethodInvokeExpression(                                                 // Assigning from a method return.
        new CodeMethodReferenceExpression(                                          // Identifying the class.
            new CodeTypeReferenceExpression(typeof(Path)),                          // Class to invoke method on.
            "GetFileName"),                                                         // Name of the method to invoke.
        new CodeExpression[] { new CodeVariableReferenceExpression("file1") }));    // Single parameter identifying a variable.

string sourceCode;

using (StringWriter writer = new StringWriter())
{
    var csProvider = CodeDomProvider.CreateProvider("CSharp");
    csProvider.GenerateCodeFromStatement(declareVariableFileName, writer, null);
    csProvider.GenerateCodeFromStatement(assignGetFileName, writer, null);

    sourceCode = writer.ToString();

    // sourceCode will now be...
    // string FileName = string.Empty;
    // FileName = System.IO.Path.GetFileName(file1);
}