繁体   English   中英

在C#中使用CodeDOM将值分配给变量

[英]Assign value to variable using CodeDOM in C#

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

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

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

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

但无法使用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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM