.Net 按键获取对象的属性值,任意深度

use*_*890 2 c# properties dynamic

我希望能够将对象属性的值访问到任何深度,只有该属性的字符串键。此外,如果可能,在 List 属性上使用集合索引。因此,如果我有字符串“Person.Surname”,那么我可以从实例化 CaseConductor 对象中获取值“Smith”。所以给出一些像这样的设置代码......

//- Load a caseConductor
var caseConductor = new CaseConductor();
caseConductor.CaseID = "A00001"; 
// person 
caseConductor.Person = new Person();
caseConductor.Person.Surname = "Smith" ;
caseConductor.Person.DOB = DateTime.Now ; 
// case note list
caseConductor.CaseNoteList = new List<Note>();
caseConductor.CaseNoteList.Add(new Note { NoteText = "A-1" , NoteDt  = DateTime.Now });
caseConductor.CaseNoteList.Add(new Note { NoteText = "B-2", NoteDt = DateTime.Now });
// I could do this ...
object val = caseConductor.SomeCleverFunction("Person.Surname");
// or this ...
object val = caseConductor.SomeCleverFunction("CaseNoteList[0].NoteText");
Run Code Online (Sandbox Code Playgroud)

以前有人这样做过吗?这里有一些设置类...

class Note
    {
        public Guid NoteID { get; set; }
        public string NoteText { get; set; }
        public DateTime? NoteDt { get; set; }
    }
    public class Person
    {
        public Guid PersonID { get; set; }
        public string Surname { get; set; }
        public string Forename { get; set; }
        public DateTime? DOB { get; set; }
    }
    class CaseConductor
    {
        public String CaseID{get;set;}
        public Person Person { get; set; }
        public List<Note> CaseNoteList { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

我们的用例是使用 open xml sdk 2 在 word dcoument 模板中迭代一系列适当命名的内容控件,并将值插入新创建的 word 文档中,就像这样......

List<SdtElement> ccList = wordprocessingDocument.MainDocumentPart.Document.Descendants<SdtElement>().ToList();
foreach (var cc in ccList)
{
  string alias = cc.SdtProperties.GetFirstChild<SdtAlias>().Val.Value;
  switch (cc.GetType().Name)
  {
    case "SdtRun":
      SdtRun thisRun = (SdtRun)cc;
      //thisRun.Descendants<Text>().First().Text  = theValueToBePoked ; 
      break;
   }
}
Run Code Online (Sandbox Code Playgroud)

Ali*_*tad 5

使用好的旧反射。我已经测试过,这确实有效:

    public static object GetValue(object o, string propertyName)
    {
        Type type = o.GetType();
        PropertyInfo propertyInfo = type.GetProperties(BindingFlags.Public | BindingFlags.Instance ).Where(x => x.Name == propertyName).FirstOrDefault();
        if(propertyInfo!=null)
        {
            return propertyInfo.GetValue(o, BindingFlags.Instance, null, null, null);
        }
        else
        {
            return null; // or throw exception 
        }
    }
Run Code Online (Sandbox Code Playgroud)