是否可以在.net 4.0中拥有动态对象属性

时间:2012-10-01 09:12:04

标签: c# asp.net object while-loop

我想基于循环迭代向对象添加新属性,这可能在.Net中吗?我想这样做的原因是我循环遍历excel电子表格中的行,并且对于每个成功读取的行,我想创建一个新的动态对象属性。因此,当循环完成时,我可以简单地将对象传递给方法并记录所有记录。

到目前为止,请参阅下面的代码:

    protected void ReadData(string filePath, bool upload)
    {
        StringBuilder sb = new StringBuilder();

        #region upload
        if (upload == true) // CSV file upload chosen
        {

            using (CsvReader csv = new CsvReader(new StreamReader(filePath), true)) // Cache CSV file to memory
            {
                int fieldCount = csv.FieldCount; // Total number of fields per row
                string[] headers = csv.GetFieldHeaders(); // Correct CSV headers stored in array 

                SortedList<int, string> errorList = new SortedList<int, string>(); // This list will contain error values
                ORCData data = new ORCData();

                bool errorFlag = false;
                int errorCount = 0;

                // Check if headers are correct first before reading data
                if (headers[0] != "first name" || headers[1] != "last name" || headers[2] != "job title" || headers[3] != "email address" || headers[4] != "telephone number" || headers[5] != "company" || headers[6] != "research manager" || headers[7] != "user card number")
                {
                    sb.Append("Headers are incorrect");
                }

                else
                {
                    while (csv.ReadNextRecord())
                        try
                        {
                            //Check csv obj data for valid values
                            for (int i = 0; i < fieldCount; i++)
                            {
                                if (i == 0 || i == 1) // FirstName and LastName
                                {
                                    if (Regex.IsMatch(csv[i].ToString(), "^[a-z]+$", RegexOptions.IgnoreCase) == false) //REGEX letters only min of 5 char max of 20
                                    {
                                        errorList.Add(errorCount, csv[i]);
                                        errorCount += 1;
                                        errorFlag = true;
                                        string text = csv[i].ToString();
                                    }
                                }
                            }

                            if (errorFlag == true)
                            {
                                sb.Append("<b>" + "Number of Error: " + errorCount + "</b>");
                                sb.Append("<ul>");
                                foreach (KeyValuePair<int, string> key in errorList)
                                {
                                    sb.Append("<li>" + key.Value + "</li>");
                                }
                            }
                            else // All validation checks equaled to false. Create User
                            {

                                string message = ORCLdap.CreateUserAccount(rootLDAPPath, svcUsername, svcPassword, csv[0], csv[1], csv[2], csv[3], csv[4], csv[5], csv[7]);
                                // TODO: Add to object here
                                sb.Append(message);
                                //sb.Append("<b>New user data uploaded successfully</b>");
                            }

                        }// end of try



                        catch (Exception ex)
                        {
                            sb.Append(ex.ToString());
                        }

                        finally
                        {
                            lblMessage.Text = sb.ToString();
                            sb.Remove(0, sb.Length);
                            hdnRdoSelection.Value = "1";
                        }
                }
            }

        }
        #endregion

我之前从未尝试过这样做,因此我不确定如何接近它,但任何帮助都会很棒。感谢。

3 个答案:

答案 0 :(得分:1)

  

我想基于循环迭代向对象添加新属性,这可能在.Net吗?

排序。您可能希望使用ExpandoObject,在添加属性时将其视为IDictionary<string, object>

话虽如此,如果你以后不打算尝试将这些属性用作属性,你真的需要它们作为属性吗?为什么不使用Dictionary<string, object>开头?

答案 1 :(得分:0)

是的,您可以使用ExpandoObject。只需指定所需的属性,它就会假设这些属性。

答案 2 :(得分:0)

dynamic settings= new ExpandoObject();