jeudi 21 juin 2018

C# get property value from object using custom attribute

I have this POCO class with properties that use a custom attribute:

Application status flags POCO class

public class ApplicationStatusFlags
    {
        public int ApplicationId { get; set; }

        [SectionFlag("APPLICANTPERSONALDETAILS")]
        public bool PersonalDetailsStatus { get; set; }

        [SectionFlag("APPLICANTECREGISTRATION")]
        public bool EcRegistrationStatus { get; set; }

        [SectionFlag("APPLICANTCV")]
        public bool CvUpload { get; set; }

        [SectionFlag("APPLICANTSTATEMENT")]
        public bool IceAttributeStatement { get; set; }

        [SectionFlag("APPLICANTCPD")]
        public bool CpdUpload { get; set; }

        [SectionFlag("APPLICANTORGCHART")]
        public bool OrgChartUpload { get; set; }

        [SectionFlag("APPLICANTSPONSORDETAILS")]
        public bool SponsorDetails { get; set; }
    }

Section flag attribute class

 [AttributeUsage(AttributeTargets.All)]
    public class SectionFlagAttribute : Attribute
    {
        /// <summary>
        /// This constructor takes name of attribute
        /// </summary>
        /// <param name="name"></param>
        public SectionFlagAttribute(string name)
        {
            Name = name;
        }

        public virtual string Name { get; }
    }

I'm trying to get the value of one of these properties by using a string with the section flag name.

So if var foo = "APPLICANTSPONSORDETAILS" I would get the boolean value of SponsorDetails.

Sample code

    updateAppStatusFlag.ApplicationId = applicationId;

    var applicationStatuses =
        await _applicationService
            .UpdateApplicationStatusFlagsAsync<ApplicationStatusFlags>(updateAppStatusFlag);

    var foo = "APPLICANTSPONSORDETAILS";

Any ideas how to do this? I know I can use reflection but I've had problems getting it to work.

Thanks





Aucun commentaire:

Enregistrer un commentaire