2016-02-19 84 views
0

我已经使用CodeDOM生成C#代码,但是我无法为后面的语句行生成代码。在C#中使用CodeDOM将变量赋值给变量#

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

从上面的代码,我用下面的代码片段

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

,但不能使用CodeDOM的第二行中添加代码编写的代码的第一道防线。所以,请让我知道我该如何实现它。

+0

你必须使用['CodeAssignStatement'](https://msdn.microsoft.com/it-it/library/system.codedom.codeassignstatement(V = vs.110)的.aspx) – xanatos

+0

我有使用CodeAssignStatement生成以下代码行。 (CodeVariableReferenceExpression(“VPath”),new CodeTypeReferenceExpression(new CodeTypeReference(“VPath + \”\\\\\“+ arr [arr.Length - 1]”))); 但它用'。'取代了'+'。在生成的代码中。我该如何解决它。 – Pankaj

+0

@Pankaj如果您不打算引用某个类型,请勿使用“CodeTypeReference”。另外,这对我来说似乎是一个新问题,所以你应该在一个新问题中提出这个问题。 – svick

回答

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