簡體   English   中英

C#自定義屬性屬性反射

[英]C# Custom Property Attribute Reflection

構建一個OpenGraph .NET解析器,但卡在屬性綁定中。 我簡單地獲取HTML文檔並使用HtmlAgilityPack對其進行解析。 之后,我要檢查每個節點的特定OpenGraph密鑰:

自定義屬性

public class OpenGraphAttribute : Attribute
{
    public string Name { get; set; }

    public OpenGraphAttribute(string name)
    {
        Name = name;
    }
}

集裝箱類

public class OGVideoContainer
{
    [OpenGraphAttribute("og:video:url")]
    public string DefaultUrl { get; set; }

    [OpenGraphAttribute("og:video:secure_url")]
    public string SecureUrl { get; set; }

    [OpenGraphAttribute("og:video:type")]
    public string Type { get; set; }

    [OpenGraphAttribute("og:video:width")]
    public string Width { get; set; }

    [OpenGraphAttribute("og:video:height")]
    public string Height { get; set; }

    [OpenGraphAttribute("og:video:url")]
    public string Url { get; set; }
}

解析器

 public OGVideoContainer ParseVideo(HtmlDocument doc)
 {
     var result = new OGVideoContainer();
     var parseableAttr = typeof(OGVideoContainer).GetProperties();
     foreach (var prop in parseableAttr)
     {
        var ca = prop.GetCustomAttributes(true).ElementAtOrDefault(0) as OpenGraphAttribute;
        if (doc.DocumentNode.SelectSingleNode(String.Format("/html/head/meta[@property='{0}']", ca.Name)) != null)
        {
            // i am stuck here how can i access the result.propery value?
        }
    }

    return result;
}

但是卡在result.parameter綁定上。 我必須為result.DefaultUrl分配相應的自定義屬性名稱值。 如何才能做到這一點?

謝謝你的幫助。

使用prop.GetValue(result)來獲取屬性值。

謝謝。 設置器可以反映如下:

        var targets = result.GetType().GetProperties();   
        targets.FirstOrDefault(m => m.Name == prop.Name).SetValue(result, "Nice String here");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM