我正在尝试使用Roslyn来获取对该属性的支持字段的符号(FieldSymbol)的引用,但是AssociatedPropertyOrEvent为null。 这是单元测试失败。
[Test]
public void Get_BackingField_for_Property()
{
var sourceCode = @" public class Player
{
private Person _MyPerson;
public virtual Person MyPerson
{
get { return _MyPerson; }
}
public virtual void Set(Person person)
{
_MyPerson = person;
}
}";
var syntaxTree = SyntaxTree.ParseText(sourceCode);
var mscorlib = MetadataReference.CreateAssemblyReference(
"mscorlib");
var compilation = Compilation.Create("HelloWorld")
.AddReferences(mscorlib)
.AddSyntaxTrees(syntaxTree);
//var semanticModel = compilation.GetSemanticModel(syntaxTree);
var classSymbol =
compilation.GetTypeByMetadataName("Player");
Assert.That(classSymbol,Is.Not.Null, "class");
var propertySymbol = classSymbol.GetMembers().Where(x => x.Kind == SymbolKind.Property);
Assert.That(propertySymbol, Is.Not.Null, "property");
var backingField = classSymbol.GetMembers().Where(x=>x.Kind== SymbolKind.Field).Cast<FieldSymbol>().First();
Assert.That(backingField.AssociatedPropertyOrEvent, Is.Not.Null,"backing field");
更新:对于任何尝试执行相同操作的人来说,INotifyPropertyChaged示例都有代码可以获取属性的支持字段。我修改它以满足我的需要。这是代码
internal static IFieldSymbol GetBackingField(this IPropertySymbol property, ISemanticModel semanticModel)
{
var propertyDelcarationSyntax = (PropertyDeclarationSyntax)property.DeclaringSyntaxNodes.First();
var getter = propertyDelcarationSyntax.AccessorList.Accessors.First(a => a.Kind == SyntaxKind.GetAccessorDeclaration);
return GetBackingFieldFromGetter(getter, semanticModel);
}
private static IFieldSymbol GetBackingFieldFromGetter(AccessorDeclarationSyntax getter, ISemanticModel semanticModel)
{
// The getter should have a body containing a single return of a backing field.
if (getter.Body == null)
{
throw new Exception("Missing a getter body for property " + semanticModel.GetDeclaredSymbol(getter.Parent).Name);
}
var statements = getter.Body.Statements;
if (statements.Count != 1)
{
throw new Exception("Getter body has more then one statement for property " + semanticModel.GetDeclaredSymbol(getter.Parent).Name);
}
var returnStatement = statements.Single() as ReturnStatementSyntax;
if (returnStatement == null || returnStatement.Expression == null)
{
throw new Exception("Getter body is missing a return statement for property " + semanticModel.GetDeclaredSymbol(getter.Parent).Name);
}
return semanticModel.GetSymbolInfo(returnStatement.Expression).Symbol as IFieldSymbol;
}
答案 0 :(得分:4)
AssociatedPropertyOrEvent
的文档说:
如果此字段用作自动生成的属性或类字段事件的后备变量,则返回该属性/事件。否则返回null。
由于您的字段与任何autoproperties无关,AssociatedPropertyOrEvent
会正确返回null
。
一般来说,您所要求的是不可能的,因为可能有许多属性可以访问同一个字段。
答案 1 :(得分:0)
您只能使用当前的API进行其他方式。使用GetMembers
获取所有这些内容,然后找到AssociatedPropertyOrEvent
是您想要的属性的字段。