代码之家  ›  专栏  ›  技术社区  ›  Huma Ali

如何在c中向列表项添加对象#

  •  0
  • Huma Ali  · 技术社区  · 9 年前

    我有以下课程:

    public class QualifyResponse
    {       
        List<ProviderQualifyResponse> _providerList = new List<ProviderQualifyResponse>();
    
        public List<ProviderQualifyResponse> ProviderList
        {
            get { return _providerList; }
            set { _providerList = value; }
        }
    }
    
    public class ProviderQualifyResponse
    {
        private string _providerCode = string.Empty;
    
        public string ProviderCode
        {
            get { return _providerCode; }
            set { _providerCode = value; }
        }
    
        private List<QuestionGroup> _questionGroupList = new List<QuestionGroup>();
    
        public List<QuestionGroup> QuestionGroupList
        {
            get { return _questionGroupList; }
            set { _questionGroupList = value; }
        }
    }
    

    我有 QualifyResponse 对象,其中填充了 ProviderQualifyResponse 但是 QuestionGroupList 是空的。现在我想填补 问题组列表 .当我尝试这样做时:

    QualifyResponse qualifyResponse = response;
    qualifyResponse.ProviderList.QuestionGroupList = new List<DataTypes.BuyFlow.Entities.QuestionGroup>();
    

    我得到一个错误:

    System.Collections.Generic。“列表”没有 包含“QuestionGroupList”的定义,并且没有扩展方法 “QuestionGroupList”接受类型为的第一个参数 'System.Collections.Generic。“列表”可能是 找到(是否缺少使用指令或程序集引用?)

    如何添加 List<QuestionGroup> 我的 qualifyResponse.ProviderList ?

    3 回复  |  直到 9 年前
        1
  •  2
  •   TheJP    9 年前

    错误是以下表达式:

    qualifyResponse.ProviderList.QuestionGroupList
    

    ProviderList属于List类型。您必须更改它,以便填充正确的项目。像这样的东西:

    int index = ...;
    qualifyResponse.ProviderList[index].QuestionGroupList = ...
    
        2
  •  1
  •   Victor Leontyev    9 年前

    问题是QuestionGroupList是类ProviderQualifyResponse的属性,若您想添加列表,需要将其分配给对象的属性。 示例如何为所有提供商执行此操作:

    QualifyResponse qualifyResponse = response;
    foreach(var provider in qualifyResponse.ProviderList)
    {
         provider.QuestionGroupList = new List<DataTypes.BuyFlow.Entities.QuestionGroup>();
    }
    
        3
  •  1
  •   Chris Pickford    9 年前

    鉴于 qualifyResponse.ProviderList 属于类型 List<ProviderQualifyResponse> ,您正在尝试访问 List.QuestionGroupList ,它不作为错误状态存在。

    您要么需要遍历列表中的实例以访问实例属性(如果这是您的意图),要么从希望实例化的列表中选择一个实例。

    QualifyResponse qualifyResponse = response;
    foreach (var providerQualifyResponse in qualifyResponse.ProviderList)
    {
        providerQualifyResponse.QuestionGroupList = new List<DataTypes.BuyFlow.Entities.QuestionGroup>();
    }
    
    推荐文章