Вопрос

I have defined a new custom attribute XPath, and applied that attribute to various properties of my class

public class Appointment
{
    [XPath("appt/@id")]
    public long Id { get; set; }

    [XPath("appt/@uid")]
    public string UniqueId { get; set; }
}

I know how to reflect against the class as a whole to retrieve all of the attributes, but I would like a way to reflect against a particular property (preferably without passing in the string name of the property)

Optimally I would be able to create an extension method (or some other type of helper) that would allow me to do something like one of the following :

appointment.Id.Xpath();

or

GetXpath(appointment.Id)

Any leads?

Это было полезно?

Решение

You can do this to get the XPathAttribute associated with a property:

var attr = (XPathAttribute)typeof(Appointment)
               .GetProperty("Id")
               .GetCustomAttributes(typeof(XPathAttribute), true)[0];

You could wrap this in a method using an Expression like this:

public static string GetXPath<T>(Expression<Func<T>> expr)
{
    var me = expr.Body as MemberExpression;
    if (me != null)
    {
        var attr = (XPathAttribute[])me.Member.GetCustomAttributes(typeof(XPathAttribute), true);
        if (attr.Length > 0)
        {
            return attr[0].Value;
        }
    }
    return string.Empty;
}

And call it like this:

Appointment appointment = new Appointment();
GetXPath(() => appointment.Id)  // appt/@id

Or if you prefer to be able to call this without having an object instance to reference:

public static string GetXPath<T, TProp>(Expression<Func<T, TProp>> expr)
{
    var me = expr.Body as MemberExpression;
    if (me != null)
    {
        var attr = (XPathAttribute[])me.Member.GetCustomAttributes(typeof(XPathAttribute), true);
        if (attr.Length > 0)
        {
            return attr[0].Value;
        }
    }
    return string.Empty;
}

And call it like this:

GetXPath<Appointment>(x => x.Id); // appt/@id

Другие советы

Second method should actually be:

   GetXPath<Appointment, long>(x => x.Id); // appt/@id
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top