您可以这样做以获取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