简体   繁体   中英

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";

    var type = applicationStatuses.GetType();

    var test = type.
            GetCustomAttributes(false)
            .OfType<SectionFlagAttribute>()
            .SingleOrDefault()
                       ?.Name == foo;

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

Thanks

In you example, you're getting the customattributes of the class instead of the properties.

Here is an example:

private object GetValueBySectionFlag(object obj, string flagName)
{
    // get the type:
    var objType = obj.GetType();

                // iterate the properties
    var prop = (from property in objType.GetProperties()
                // iterate it's attributes
                from attrib in property.GetCustomAttributes(typeof(SectionFlagAttribute), false).Cast<SectionFlagAttribute>()
                // filter on the name
                where attrib.Name == flagName
                // select the propertyInfo
                select property).FirstOrDefault();

    // use the propertyinfo to get the instance->property value
    return prop?.GetValue(obj);
}

Note: this will return only the first property which contains the SectionFlagAttribute with the right name. You could modify the method to return multiple values. (like a collection of propertyname/value)


Usage:

// a test instance.
var obj = new ApplicationStatusFlags { IceAttributeStatement = true };

// get the value by SectionFlag name
var iceAttributeStatement = GetValueBySectionFlag(obj, "APPLICANTSTATEMENT");

If the returned value is null then the flag is not found or the property's value is null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM