2016-02-19 82 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); 
}