代码之家  ›  专栏  ›  技术社区  ›  Bern

从类型访问jsonobject title

  •  1
  • Bern  · 技术社区  · 7 年前

    我有一个带有json.net jsonobject属性的类,我设置了如下标题:

    [JsonObject(Title="SomeOtherClassTitle")]
    public class MyClass
    {
    }
    

    当我以类型管理类时,我希望能够访问“someotherclasstitle”标题。所以我的目标是这个但我不确定

    var someType = typeof(MyClass);
    var customTitle = ??; // Insert code here which returns "SomeOtherClassTitle"
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Nkosi    7 年前

    使用可通过从类中获取属性并调用所需成员获得的反射

    var attribute = someType.GetCustomAttribute(typeof(JsonObjectAttribute)) as JsonObjectAttribute;
    if(attribute != null) {
        var title = attribute.Title;
    }