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

本文关键字:变量 赋值 CodeDOM | 更新日期: 2023-09-27 18:35:17

我已经使用 CodeDOM 生成 C# 代码,但我无法为以下语句行生成代码。

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

从上面的代码中,我使用以下代码片段编写了第一行的代码

using(CodeVariableDeclarationStatement strFileName = 
    new CodeVariableDeclarationStatement(typeof(string), "strFileName",
    new CodeTypeReferenceExpression("String.Empty"));) 

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

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

// 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);
}