예제 #1
0
        private static void FindClassSyntax()
        {
            // Firstly, let's use a SyntaxWalker to explore the SyntaxTree for our document.
            // We want to locate the first class declaration in the document so we can perform
            // some semantic analysis on it later.
            var walker = new ClassDeclarationSyntaxWalker();

            walker.Visit(SyntaxTree.GetRoot());

            var classDeclaration = walker.ClassDeclaration;

            if (classDeclaration == null)
            {
                return;
            }

            var baseList = classDeclaration.BaseList;

            if (baseList == null || !baseList.Types.Any())
            {
                return;
            }

            // Here we use the Compilation to resolve the type symbol for 'System.Attribute'
            // As we loaded a reference to the 'System' assembly to our project, the 'System.Attribute'
            // type will exist in the semantic state of the compilation.
            var attributeType = Compilation.GetTypeByMetadataName("System.Attribute");

            //
            bool derivesFromAttribute = false;

            foreach (var type in baseList.Types)
            {
                var baseType = type as SimpleBaseTypeSyntax;

                if (baseType != null)
                {
                    var typeInfo = SemanticModel.GetTypeInfo(baseType.Type);

                    if (typeInfo.Type != null &&
                        typeInfo.Type.TypeKind != TypeKind.Interface &&
                        SymbolHelper.DerivesFrom(typeInfo.Type, attributeType))
                    {
                        derivesFromAttribute = true;
                        break;
                    }
                }
            }

            if (!derivesFromAttribute)
            {
                return;
            }

            ClassDeclarationSyntax = classDeclaration;
        }