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