3

看下面的代码

private static List<ExpandoObject> GetDBDetails()
        {
            var directoryPath = Environment.CurrentDirectory.Replace("\\bin\\Debug", "\\DataSource");
            var filePath = Path.Combine(directoryPath, "DBDetail.xml");
            try
            {
                //Load xml
                XDocument xdoc = XDocument.Load(filePath);
                if (xdoc == null) return null;


                List<ExpandoObject> dbDetails = (from dbDetail in xdoc.Descendants("database")
                                       select new ExpandoObject
                                            {
                                                DBDetailId = Convert.ToInt32(dbDetail.Attribute("dbDetailId").Value),
                                                DBServerId = Convert.ToInt32(dbDetail.Attribute("dbServerID").Value)
                                                                                                });
               return dbDetails;
            }
            catch (Exception ex)
            {
                McAfee.EnterpriseLibrary.Logging.LogUtil.LogEntry(ex, System.Diagnostics.TraceEventType.Critical);
                return null;
            }
        }

我收到错误

System.Dynamic.ExpandoObject' 不包含 'DBDetailId' 的定义 System.Dynamic.ExpandoObject' 不包含 'DBServerId' 的定义

如何纠正这种情况?

4

1 回答 1

4

您需要将其ExpandoObject转换为dynamic

 xdoc.Descendants("database")
            .Select(dbDetail =>
                        {
                            dynamic expandoObj = new ExpandoObject();
                            expandoObj.DBDetailId = Convert.ToInt32(dbDetail.Attribute("dbDetailId").Value);
                            expandoObj.DBServerId = Convert.ToInt32(dbDetail.Attribute("dbServerID").Value);
                            return (ExpandoObject) expandoObj;
                        })
            .ToList();

您也可以投射ExpandoObjectIDictionary<string, object>

var x = new ExpandoObject() as IDictionary<string, object>;
x.Add("DBDetailId", Convert.ToInt32(dbDetail.Attribute("dbDetailId").Value));
x.Add("DBServerId", Convert.ToInt32(dbDetail.Attribute("dbServerID").Value));
于 2013-05-08T10:51:49.280 回答