samedi 27 juin 2015

Technique for generating valid type names with generic in Roslyn

I'm trying out a few possible techniques for generating a dynamic proxy of a C# interface at runtime. So far I've found Roslyn has taken me a fair away without too much friction, but I'm a bit stuck on dealing with generic types. In particular, getting type names to parse.

My basic workflow is:

  • Build the scaffolding for usings, a namespace and a class as a CompilationUnitSyntax
  • Inspect the interface getting proxied
  • For every method on the interface, use the MethodInfo to build a MethodDeclarationSyntax using SyntaxFactory.MethodDeclaration, with the goal to my new dynamic class

Here's an example of the issue I'm puzzling over. At this point it seems that I need to parse a string to get a TypeSyntax (in this case for the return type), and the only place I can take it is from methodInfo.ReturnType.Name:

var methodDecl = SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName(methodInfo.ReturnType.Name), methodInfo.Name);

The problem is SyntaxFactory.ParseTypeName is expecting 'valid' C# syntax type declarations, for example List<string>, but accessing the Name or FullName properties are in the form:

{Name = "List`1" FullName =
"System.Collections.Generic.List`1[[UnitTests.SamplePoco, UnitTests,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]"}   System.Type
{System.RuntimeType}

which obviously won't parse, with the backticks, lack of angle brackets etc.

Is there a better bridge between Reflection style classes (MethodInfo, Types) and Roslyn syntax units? I'm also trying out a pure reflection emit style solution as well, but wanted to see if I could get a Roslyn based one going here.





Aucun commentaire:

Enregistrer un commentaire