public static bool SetValidNumber(Student student, int nr)
        {
            // Verifica se propriedade Nr de student tem atributo o Validator aplicado.
            // Se sim, verifica se studentNum é um argumento válido, executando o método
            // NumberGreaterThan20000. Se o número for válido, faz set do número ao student.

            // Realize o método NumberGreaterThan20000, que se encontra na classe ValidatorAttribute
            // Otimize o código para criar o atributo apenas uma vez.
            if (!Created)
            {
                // Get student type
                Type type = student.GetType();
                // Get Nr property
                PropertyInfo pi = type.GetProperty("Nr");
                // Get custom attribute - parameters: attribute type, inherit = false
                att = (ValidatorAttribute)pi.GetCustomAttribute(typeof(ValidatorAttribute), false);
                // Change Created
                Created = true;
            }
            bool result = true;

            if (att != null)
            {
                result = att.IsValidNumber(nr);
                if (result)
                {
                    student.Nr = nr;
                }
            }
            return(result);
        }
Example #2
0
        // ...
        public static bool IsValid(Type studentType, int value)
        {
            // Verifica se propriedade Nr tem atributo Validator aplicado.
            // Se sim, verifica se value é um argumento válido, executando o método
            // NumberGreaterThan20000.
            // O método NumberGreaterThan20000 encontra-se na classe ValidatorAttribute
            // Otimize o código para criar o atributo apenas uma vez.

            /*obtemos todas as propriedades de Student: Nr, Name*/
            var propertiesOfStudent = studentType.GetProperties();

            /*verifica se a propriedade Nr tem o atibuto Validator*/
            var hasAttr = Attribute.IsDefined(studentType.GetProperty("Nr"), typeof(ValidatorAttribute));


            if (hasAttr)
            {
                return(ValidatorAttribute.NumberGreaterThan20000(value));
            }

            else
            {
                return(false);
            }
        }