2014-10-29 106 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