代码之家  ›  专栏  ›  技术社区  ›  Jason Coyne

如何从属性引用中检索自定义属性值。

  •  0
  • Jason Coyne  · 技术社区  · 11 年前

    我定义了一个新的自定义属性XPath,并将该属性应用于类的各种财产

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

    我知道如何对整个类进行反射以检索所有属性,但我希望有一种方法来对特定属性进行反射(最好不传入属性的字符串名称)

    最理想的情况是,我可以创建一个扩展方法(或其他类型的帮助程序),允许我做以下事情之一:

    appointment.Id.Xpath();
    

    GetXpath(appointment.Id)
    

    有线索吗?

    2 回复  |  直到 11 年前
        1
  •  2
  •   p.s.w.g    11 年前

    你可以这样做来获得 XPathAttribute 与属性关联:

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

    您可以使用 Expression 这样地:

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

    并这样称呼它:

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

    或者,如果您希望能够在没有要引用的对象实例的情况下调用它:

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

    并这样称呼它:

    GetXPath<Appointment>(x => x.Id); // appt/@id
    
        2
  •  1
  •   user2926618    11 年前

    第二种方法实际上应该是:

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