C#使用ExpandoObject类动态扩展属性

101 阅读1分钟

设置属性

List<ExpandoObject> objs = new List<ExpandoObject>();
            foreach (var item in query.ToList())
            {
                dynamic tempObj = new ExpandoObject();
                tempObj.Name = item.Person.Name;
                tempObj.Code = item.Person.Code;
                tempObj.Deptname = item.Person.DeptName;
                tempObj.Subjectname = item.Subject.Name;
                foreach (var propertieInfo in item.GetType().GetProperties())
                {
                    var propKey = propertieInfo.Name;
                    var propValue = propertieInfo.GetValue(item);
                    ((IDictionary<string, object>)tempObj).Add(propKey, propValue);
                }
                objs.Add(tempObj);
            }

使用属性

  var tempDict = ((ExpandoObject)item).ToImmutableDictionary();
  tempDict.TryGetValue(fieldName, out object oneCellValue);