gpt4 book ai didi

c# - CallerMemberNameAttribute 和 Roslyn

转载 作者:行者123 更新时间:2023-11-30 14:59:07 28 4
gpt4 key购买 nike

Roslyn CTP 是否支持 CallerMemberNameAttribute 和其他类似的东西?

我有一个带有多个参数的方法,其中一些是必需的,还有一个带有默认值的参数,用 CallerMemberName 属性标记。

我正在通过 Roslyn 生成对该方法的调用,仅传递强制参数,并期望它也为编译器生成的参数生成值,但这并没有发生,它们具有默认值。

这是 Roslyn 当前版本的限制,还是我做错了什么?

最佳答案

What's New in the Microsoft "Roslyn" September 2012 CTP ,值得注意的是:

The full C# 4 and Visual Basic 10 languages are supported by the parser, but there are several language features that are not yet completely implemented in the current Roslyn compilers.

Caller Information .NET Framework 4.5(C# 5.0 和 Visual Basic 11)中引入了该功能。因此,Roslyn 在当前版本中不支持它。然而,获取调用者信息可以使用类似以下代码片段的方式完成,来自“Can I get function caller/callee information from Roslyn?”在 MSDN 论坛中提出的问题:

var syntaxTree = SyntaxTree.ParseCompilationUnit(code);

var semanticModel = Compilation.Create("compilation")
.AddSyntaxTrees(syntaxTree)
.AddReferences(new AssemblyFileReference(typeof(object).Assembly.Location))
.GetSemanticModel(syntaxTree);

var baz = syntaxTree.Root
.DescendentNodes()
.OfType<ClassDeclarationSyntax>()
.Single(m => m.Identifier.ValueText == "C1")
.ChildNodes()
.OfType<MethodDeclarationSyntax>()
.Single(m => m.Identifier.ValueText == "Baz");

var bazSymbol = semanticModel.GetDeclaredSymbol(baz);

var invocations = syntaxTree.Root
.DescendentNodes()
.OfType<InvocationExpressionSyntax>();

var bazInvocations = invocations
.Where(i => semanticModel.GetSemanticInfo(i).Symbol == bazSymbol);

关于c# - CallerMemberNameAttribute 和 Roslyn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17270173/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com