从C#中返回的对象访问属性

时间:2018-12-07 12:47:15

标签: c#

美好的一天。 我一直在想应该是一个新手问题,我正在从数据层中的方法返回一个对象,但我希望能够访问说

RuleListCollection.ruleName

但是我在列表中将整个对象发回给我,我如何访问上面的属性。 这是返回对象的数据层中的代码

        public List<TpRuleMapConfig>  GetTpRuleList()
    {
        StringBuilder query = new StringBuilder();
        TpRuleMapConfig tpRuleMapConfig = new TpRuleMapConfig();
        List<TpRuleMapConfig> tpRuleList = new List<TpRuleMapConfig>();


        try
        {
            query.AppendLine("SELECT maestro.TPRuleMapConfig.LINK,maestro.TPRuleMapConfig.TPRULENAME,maestro.TPRuleMapConfig.SBSARULENAME,");
            query.AppendLine(" maestro.COUNTINGCONFIG.RULETYPE,maestro.TPRuleMapConfig.ISPREADVRULE FROM maestro.TPRuleMapConfig");
            query.AppendLine("INNER JOIN maestro.COUNTINGCONFIG on maestro.COUNTINGCONFIG.NAME=TPRuleMapConfig.SBSARULENAME;");

            using (SqlConnection con = new SqlConnection(this._connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(query.ToString()))
                {
                    con.Open();
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.Text;

                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            tpRuleMapConfig.Link = reader["LINK"].ToString();
                            tpRuleMapConfig.TpRuleName = reader["TPRULENAME"].ToString();
                            tpRuleMapConfig.SbsaRuleName = reader["SBSARULENAME"].ToString();
                            tpRuleMapConfig.RuleType = Convert.ToInt32(reader["RULETYPE"]);
                            tpRuleMapConfig.IsPreadVised = reader["ISPREADVRULE"].GetBooleanValue();

                            tpRuleList.Add((tpRuleMapConfig));
                        }
                    }

                }
            }
        }
        catch (Exception)
        {

            throw;
        }

        return tpRuleList;
    }

这是我要访问该值的地方

        DataLayer datalayer = new DataLayer(this._connectionString);
        cmbRuleType.DataSource = datalayer.GetTpRuleList().TpRuleName;

1 个答案:

答案 0 :(得分:3)

您的方法返回List个对象,而不是单个对象。您可以遍历列表并读取列表中每个对象的RuleName

var tpRuleList = datalayer.GetTpRuleList();
foreach (var tpRule in tpRuleList)
{
    var tpRuleName = tpRule.TpRuleName;
    // Do something with tpRuleName.
}