【发布时间】:2021-08-04 15:13:04
【问题描述】:
我想获取作为参数传递给方法的结构的大致大小。我正在使用 Roslyn 分析仪。我们要检查按值传入的结构不大于 128 字节。对于我们的目的,使用 sizeof 或 Marshal.SizeOf 就足够了。
问题在于,据我了解,I cannot use reflection to get the type in the analyzer since reflection is a runtime API。有什么办法可以规避这个问题吗?或者从 Roslyn 中可用的信息中获取结构的大致大小?以下是我迄今为止尝试过的一些事情:
private static void CheckMethodParameters(SyntaxNodeAnalysisContext context)
{
var methodDeclarationSyntax = (MethodDeclarationSyntax)context.Node;
foreach (var parameterSyntax in methodDeclarationSyntax.ParameterList.Parameters)
{
var parameterSymbol = context.SemanticModel.GetDeclaredSymbol(parameterSyntax);
if (parameterSymbol == null)
continue;
// As expected, none of these have the type I need
var entryAssembly = Assembly.GetEntryAssembly();
var callingAssembly = Assembly.GetCallingAssembly();
var executingAssemblyAssembly = Assembly.GetExecutingAssembly();
// This only gets the NamedTypeSymbol, not the type
var namedTypeSymbol = context.Compilation.GetTypeByMetadataName($"{parameterSymbol.Type.ContainingNamespace}.{parameterSymbol.Type.Name}");
// None of these work
var typeFromFullName = Type.GetType($"{parameterSymbol.Type.ContainingNamespace}.{parameterSymbol.Type.Name}, {context.Compilation.Assembly}");
var assembly = Assembly.Load(context.Compilation.Assembly.ToString());
var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location);
var type = Assembly.Load(context.Compilation.Assembly.Name).GetType($"{parameterSymbol.Type.ContainingNamespace}.{parameterSymbol.Type.Name}");
}
}
任何帮助将不胜感激。
【问题讨论】:
标签: c# .net visual-studio roslyn roslyn-code-analysis