예제 #1
0
        public static T AddEquality <T>(
            this T syntax,
            string typeName,
            IReadOnlyList <PropertyDescriptor> properties,
            bool generateRecordEquality = false)
            where T : TypeDeclarationSyntax
        {
            TypeDeclarationSyntax modified = syntax;

            var builder    = new StringBuilder();
            var codeWriter = new CodeWriter(builder);

            if (!generateRecordEquality)
            {
                modified = modified.AddImplements(TypeNames.IEquatable.WithGeneric(typeName));

                BuildObjectEqualsMethod(typeName).Build(codeWriter);
                codeWriter.Flush();
                var overrideMethod = builder.ToString();
                builder.Clear();

                modified = modified.AddMembers(
                    CSharpSyntaxTree
                    .ParseText(overrideMethod,
                               new CSharpParseOptions(kind: SourceCodeKind.Script))
                    .GetCompilationUnitRoot()
                    .Members
                    .ToArray());
            }

            BuildEqualsMethod(typeName, properties).Build(codeWriter);
            codeWriter.Flush();
            var equalsMethod = builder.ToString();

            builder.Clear();

            modified = modified.AddMembers(
                CSharpSyntaxTree
                .ParseText(
                    equalsMethod,
                    new CSharpParseOptions(kind: SourceCodeKind.Script))
                .GetCompilationUnitRoot()
                .Members
                .ToArray());


            BuildGetHashCodeMethod(properties).Build(codeWriter);
            codeWriter.Flush();
            var hashCodeMethod = builder.ToString();

            builder.Clear();
            modified = modified.AddMembers(
                CSharpSyntaxTree
                .ParseText(hashCodeMethod, new CSharpParseOptions(kind: SourceCodeKind.Script))
                .GetCompilationUnitRoot()
                .Members
                .ToArray());

            if (modified is T target)
            {
                return(target);
            }

            throw new InvalidOperationException();
        }