0

新しいカスタム属性 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)

リードはありますか?

4

2 に答える 2

2

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
于 2013-10-01T16:52:14.643 に答える