简体   繁体   中英

C# Custom Property Attribute Reflection

Building an OpenGraph .NET Parser but stuck in property binding. I simple fetch the HTML Document and parse it using HtmlAgilityPack . After that I want to check each Node for the specific OpenGraph Key:

Custom Attribute

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

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

Container Class

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

Parser

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

But stuck at the result.parameter binding. I have to assign result.DefaultUrl with the corresponding custom attribute name value. How can this be done?

Thanks for any help.

使用prop.GetValue(result)来获取属性值。

Thanks. The Setter can be reflected as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM