简体   繁体   中英

How can I get the value of a property for a class with an attribute set from a metadata class?

I had this problem and couldn't find any general solutions for it on SO, so I'm posting it here.

How can I get the value of a property for a class with an attribute set from a metadata class?

I have a custom attribute that I want to use to denote properties I'm interested in. However, that attribute must be applied through a metadata class because I'm using the class with Entity Framework.

I want to get the values of my type that are specified by the metadata that have my attribute set, but this code isn't finding the properties that are defined by the metadata.

public class PropertyAttribute : Attribute { }

[MetadataType(typeof(CarMetaData))]
public class Car
{
    [Property]
    public int FieldA { get; set; }

    public int MetaFieldA { get; set; }

    internal sealed class CarMetaData
    {
        [Property]
        public int MetaFieldA { get; set; }
    }
}

var car = new Car() { FieldA = 1234, MetaFieldA = 4321 };
var source = car;
var sourceType = source.GetType();
var props = sourceType.GetProperties().Where(p => Attribute.IsDefined(p, typeof(PropertyAttribute)));

foreach (PropertyInfo prop in props)
{
    var sourceProp = sourceType.GetProperty(prop.Name);
    var val = sourceProp.GetValue(source, null);
    //do something with val
}

This can be done by finding the metadata class type, and finding the properties of that type that have your attribute defined.

var metaAttr = (MetadataTypeAttribute)sourceType.GetCustomAttribute(typeof(MetadataTypeAttribute), true);
var metaClassType = metaAttr.MetadataClassType;

var props = metaClassType.GetProperties().Where(p => Attribute.IsDefined(p, typeof(PropertyAttribute)));

foreach (PropertyInfo prop in props)
{
    var sourceProp = sourceType.GetProperty(prop.Name);
    var val = sourceProp.GetValue(source, null);
    //do something with val
}

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