我正在挖掘一个对象,该对象包含字符串格式的“值”,这些“值”对应于嵌套在我从中获取所述值的对象中的对象和属性。IE 如果我的对象包含一个嵌套对象列表,其中包含一个联系人对象中的名称,例如名称,那么我有一个“值”,可能会读取类似“ContactInfo[0].Name”的内容。
如何验证该属性是否存在?我很确定,如果我能弄清楚第一部分,那么我可以担心以更少的难度获得价值。
我尝试过使用以下内容:
public static bool HasProperty(this object obj, string propertyName)
{
return obj.GetType().GetProperty(propertyName) != null;
}
分别使用参数“MasterInfo”、“Keys[0].KeyWord”和“Keys[1].Keyword”。
我已经尝试通过 DOT 符号将它们分解为段和我能想到的所有其他内容,但我似乎无法成功使用该方法中的关键字。总是假的。
我尝试通过将关键字分解为“。”的例程运行 MasterInfo 对象。并迭代每个部分,但结果没有变化......总是假的。
新鲜的眼睛非常受欢迎!我必须错过一些简单的和/或就在我面前的东西......
// simplified object example
public class MasterInfo
{
public int Id { get; set; }
public List<ContactInfo> Contacts {get; set;}
public Message MessageDetail { get; set; }
public List<Key> Keys { get; set; }
}
public class ContactInfo
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
public class Message
{
public int Id { get; set; }
public string MessageContent { get; set; }
}
public class Key
{
public int Id { get; set; }
public string KeyWord { get; set; }
}
// serialized JSON of what the MasterInfo class would be populated with, easier to read than with '.' notation
{
"Id" : 1,
"Contacts" : [
{
"Id" : 1,
"Name" : "Beavis",
"Email" : "beavis@asd.asd"
}
],
"MessageDetail" : {
"Id" : 23,
"MessageContent" : "Hello, %%Contacts[0].Name%%, this was sent to you at %%Contacts[0].Email%%"
},
"Keys" : [
{
"Id" : 1,
"KeyWord" : "Contacts[0].Name"
},
{
"Id" : 2,
"KeyWord" : "Contacts[0].Email"
}
]
}
// method I'm trying to use to verify the keyword (property) exists before attempting to get it's value...
public static bool HasProperty(this object obj, string propertyName)
{
return obj.GetType().GetProperty(propertyName) != null;
}
到目前为止,在评估时,一切都变成了错误的。我很确定这与我正在潜入嵌套对象的事实有关,但在这一点上我不确定任何事情。