假设您有以下代码:
var house = new {Color = "White", Area = 150};
var typeHouse = house.GetType();
var argumentTypes = typeHouse.GetGenericArguments();
argumentTypes数组有两种类型:string 和 int... 没关系 :)
但是,如果我有下一个使用 Roslyn 编译器的代码:
var tree = SyntaxTree.ParseText(@"
namespace TestRoslyn {
public class MyClass {
public void GetHouse(){
var house = new {Color = 'W', Area = 150};
}
}
}");
byte[] assembly;
var compiler = Compilation.Create("Test", new CompilationOptions(outputKind: OutputKind.DynamicallyLinkedLibrary,
usings: new[] { "System" }))
.AddSyntaxTrees(tree)
.AddReferences(new MetadataFileReference(typeof(object).Assembly.Location));
using (var stream = new MemoryStream())
{
var result = compiler.Emit(stream);
if (!result.Success)
throw new Exception("You have an error! :( ");
assembly = stream.ToArray();
}
Type[] types = Assembly.Load(assembly).GetTypes();
var argumentTypes = types[0].GetGenericArguments(); //types [0] returns the <>f__AnonymousType
然后,argumentTypes数组显示了两种通用类型,例如“Color j_ TPar”和“Area j _TPar”... :(
我的问题是:为什么在 Roslyn 示例中我无法从 Anonymous 类型中获得正确的参数类型?
如何获得“正确”的参数类型?