简体   繁体   English

C#使用自定义属性从对象获取属性值

[英]C# get property value from object using custom attribute

I have this POCO class with properties that use a custom attribute: 我有这个POCO类,其属性使用自定义属性:

Application status flags POCO class 应用程序状态标志POCO类

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 . 因此,如果var foo = "APPLICANTSPONSORDETAILS"我将获得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. 注意:这将仅返回第一个属性,该属性包含具有正确名称的SectionFlagAttribute。 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. 如果返回的值为null则找不到该标志或该属性的值为null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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