[英]Get attribute arguments with roslyn
我嘗試使用 Roslyn 獲取MyAttribute
的命名參數。
var sourceCode = (@"
public class MyAttribute : Attribute
{
public string Test { get; set; }
}
[MyAttribute(Test = ""Hello"")]
public class MyClass { }
");
var syntaxTree = CSharpSyntaxTree.ParseText(sourceCode);
var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
var compilation = CSharpCompilation.Create("MyCompilation", new[] { syntaxTree }, new[] { mscorlib });
var semanticModel = compilation.GetSemanticModel(syntaxTree);
var syntaxRoot = syntaxTree.GetRoot();
var classNode = syntaxRoot.DescendantNodes().OfType<ClassDeclarationSyntax>().Skip(1).First();
var classModel = (ITypeSymbol)semanticModel.GetDeclaredSymbol(classNode);
var firstAttribute = classModel.GetAttributes().First();
但是firstAttribute.AttributeClass.Kind
等於ErrorType
,因此firstAttribute.NamedArguments
包含任何元素。
代碼不是分析器,也不是我有更完整上下文的東西,比如解決方案。
我看不出 roslyn 缺少任何參考資料或其他內容。 我該怎么做才能全面分析屬性?
您需要完全限定Attribute
類型名稱:
var sourceCode = (@"
public class MyAttribute : System.Attribute // < here
{
public string Test { get; set; }
}
[MyAttribute(Test = ""Hello"")]
public class MyClass { }
");
然后它將按預期工作:
var firstNamedArg = firstAttribute.NamedArguments[0];
var key = firstNamedArg.Key; // "Test"
var value = firstNamedArg.Value.Value; // "Hello"
或者,您可以using System;
添加using System;
在頂部:
var sourceCode = (@"
using System;
public class MyAttribute : Attribute
{
public string Test { get; set; }
}
[MyAttribute(Test = ""Hello"")]
public class MyClass { }
");
您可以使用語法API來獲取atttribute的參數信息,而不是使用Roslyn的SemanticModel
:
var firstAttribute = classNode.AttributeLists.First().Attributes.First();
var attributeName = firstAttribute.Name.NormalizeWhitespace().ToFullString();
Console.WriteLine(attributeName);
// prints --> "MyAttribute"
var firstArgument = firstAttribute.ArgumentList.Arguments.First();
var argumentFullString = firstArgument.NormalizeWhitespace().ToFullString();
Console.WriteLine(argumentFullString);
// prints --> Test = "Hello"
var argumentName = firstArgument.NameEquals.Name.Identifier.ValueText;
Console.WriteLine(argumentName);
// prints --> Test
var argumentExpression = firstArgument.Expression.NormalizeWhitespace().ToFullString();
Console.WriteLine(argumentExpression);
// prints --> "Hello"
一旦你有你的xxxDeclaredSymbol
你就可以得到所有的屬性
var attributes = methodSymbol.GetAttributes().ToArray();
然后,您可以遍歷數組中的每個AttributeData
並使用我編寫的這個擴展,它將為您提供所有名稱+ 傳遞給屬性構造函數的值的列表,無論它們是否已命名...
// Used as a 3 value tuple for Name + TypeName + actual value
public class NameTypeAndValue
{
public string Name { get; private set; }
public string TypeFullName { get; private set; }
public object Value { get; private set; }
public NameTypeAndValue(string name, string typeFullName, object value)
{
Name = name;
TypeFullName = typeFullName;
Value = value;
}
}
public static class ITypeSymbolExtensions
{
// Converts names like `string` to `System.String`
public static string GetTypeFullName(this ITypeSymbol typeSymbol) =>
typeSymbol.SpecialType == SpecialType.None
? typeSymbol.ToDisplayString()
: typeSymbol.SpecialType.ToString().Replace("_", ".");
}
public static bool TryGetAttributeAndValues(
this AttributeData attributeData,
string attributeFullName,
SemanticModel model,
out IEnumerable<NameTypeAndValue> attributeValues)
{
var attributeValuesList = new List<NameTypeAndValue>();
var constructorParams = attributeData.AttributeConstructor.Parameters;
// Start with an indexed list of names for mandatory args
var argumentNames = constructorParams.Select(x => x.Name).ToArray();
var allArguments = attributeData.ConstructorArguments
// For unnamed args, we get the name from the array we just made
.Select((info, index) => new KeyValuePair<string, TypedConstant>(argumentNames[index], info))
// Then we use name + value from the named values
.Union(attributeData.NamedArguments.Select(x => new KeyValuePair<string, TypedConstant>(x.Key, x.Value)))
.Distinct();
foreach(var argument in allArguments)
{
attributeValuesList.Add(
new NameTypeAndValue(
name: argument.Key,
typeFullName: argument.Value.Type.GetTypeFullName(),
value: argument.Value.Value));
}
attributeValues = attributeValuesList.ToArray();
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.