简体   繁体   中英

Find a property on an object instance by it's attribute value

I have a DTO that looks like this:

public class MyDto
{
    [MyAttribute("attribute1")]
    public string Property1 {get;set;}

    [MyAttribute("attribute2")]
    public string Property2 {get;set;}
}

If I have the string "attribute1", how do I use that to get to the value of Property1 in an instance of MyDto ?

Use Reflection . Unfortunately, there's no way to obtain the property from an attribute: you have to iterate through each property and check its attribute.

Not the most robust code, but try this:

public class MyAttributeAttribute : Attribute
{
    public MyAttributeAttribute(string value)
    {
        Value=value;
    }
    public string Value { get; private set; }
}

public class MyDto
{
    [MyAttribute("attribute1")]
    public string Property1 { get; set; }

    [MyAttribute("attribute2")]
    public string Property2 { get; set; }
}

class Program
{
    static void Main(string[] args)
    {

        MyDto dto=new MyDto() { Property1="Value1", Property2="Value2" };

        string value=GetValueOf<string>(dto, "attribute1");
        // value = "Value1"
    }

    public static T GetValueOf<T>(MyDto dto, string description)
    {
        if(string.IsNullOrEmpty(description))
        {
            throw new InvalidOperationException();
        }
        var props=typeof(MyDto).GetProperties().ToArray();
        foreach(var prop in props)
        {
            var atts=prop.GetCustomAttributes(false);
            foreach(var att in atts)
            {
                if(att is MyAttributeAttribute)
                {
                    string value=(att as MyAttributeAttribute).Value;
                    if(description.Equals(value))
                    {
                        return (T)prop.GetValue(dto, null);
                    }
                }
            }
        }
        return default(T);
    }
}

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