2014-10-29 104 views
2

如何使用CodeDom.CodeMemberMethod來裝飾方法簽名async使用CodeMemberMethod創建異步方法

我想有結果:

public async Task SomeMethodAsync() 
{  
} 

有沒有辦法做到這一點WHIS CodeDom中。我結束了使用regex

public static class GenCodeParser 
{ 
    private const string AsyncKeyWordPattern = @"(?<=public class DynamicClass(\r\n)*\s*{(\r\n)*\s*public)(?=.*\s*SomeMethodAsync{1})"; 
    private const string AsyncKeyWordReplacementPattern = @" async "; 

    public static string AddAsyncKeyWordToMethodDeclaration(string sourceCode) 
    { 
     if (string.IsNullOrWhiteSpace(sourceCode)) return null; 

     try 
     { 
      var regex = new Regex(AsyncKeyWordPattern); 
      return regex.Replace(sourceCode, AsyncKeyWordReplacementPattern); 
     } 
     catch 
     { 
      return null; 
     } 
    } 
} 
+0

看來你找到了一個解決方案,你應該張貼它作爲一個答案,然後你能接受它。 – svick 2014-10-29 23:50:44

回答

2

的CodeDOM不知道什麼async,所以沒有直接的方法將它添加到你的方法。但它對你寫的東西也很寬容。

所以,你可以做的是編寫一個返回類型爲async Task的方法。當然,這不是一個有效的類型,但是如果你將該字符串寫入通常返回類型的位置,就會得到想要的結果。

例如:

new CodeMemberMethod 
    { Name = "M", ReturnType = new CodeTypeReference("async Task") } 

編譯成:

private async Task M() { 
} 
+0

真棒解決方法。謝謝! – Denis 2014-10-31 23:51:27