Exemplo n.º 1
0
        /// <summary>
        /// Returns attribute argument at the specified <paramref name="position"/> and with the given <paramref name="argumentName"/>.
        /// <para>If <paramref name="argumentName"/> is <see langword="null"/>, only <paramref name="position"/> is included in the search.</para>
        /// <para>If no appropriate argument found, returns <see langword="null"/>.</para>
        /// </summary>
        /// <param name="attribute"><see cref="AttributeSyntax"/> to get the argument of.</param>
        /// <param name="position">Position of argument to get.</param>
        /// <param name="argumentName">Name of the argument to get the location of.</param>
        /// <exception cref="ArgumentNullException"><paramref name="attribute"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="position"/> cannot be less than <c>0</c>.</exception>
        public static AttributeArgumentSyntax?GetArgument(this AttributeSyntax attribute, int position, string?argumentName = null)
        {
            if (attribute is null)
            {
                throw new ArgumentNullException(nameof(attribute));
            }

            if (position < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(position), "Argument position cannot be less than 0!");
            }

            if (attribute.ArgumentList is null)
            {
                return(null);
            }

            SeparatedSyntaxList <AttributeArgumentSyntax> arguments = attribute.ArgumentList.Arguments;

            if (!arguments.Any())
            {
                return(null);
            }

            if (string.IsNullOrWhiteSpace(argumentName))
            {
                if (position >= arguments.Count)
                {
                    return(null);
                }

                return(arguments[position]);
            }

            if (position < arguments.Count)
            {
                AttributeArgumentSyntax arg = arguments[position];

                if (arg.GetName() == argumentName)
                {
                    return(arg);
                }
            }

            return(arguments.FirstOrDefault(arg => arg.GetName() == argumentName));
        }