2016-10-03 56 views
0

我很难过。我有一个构造函数的类,看起来像这样:添加到构造类

class CClasses 
{ 
    public class CCategoryGroup : List<CCategory> 
    { 
     public string CTitle { set; get; } 
     public string CShortTitle { set; get; } 
     public CARESCategoryGroup(string ctitle, string cshorttitle) 
     { 
      this.CTitle = ctitle; 
      this.CShortTitle = cshorttitle; 
     } 
    }; 

    public class CCategory 
    { 
     public int CID { set; get; } 
     public string CName { set; get; } 
     public ImageSource CIcon { set; get; } 
     public string CUrl { set; get; } 
     public CCategory(int cid, string cname, ImageSource cicon, string curl) 
     { 
      this.CID = cid; 
      this.CName = cname; 
      this.CIcon = cicon; 
      this.CUrl = curl; 
     } 
    }; 
} 

我要添加到类的构造函数部分,像这样:

  //List<CCategoryGroup> ccategory = new List<CCategoryGroup> 
     //{ 
     // new CCategoryGroup("Dolphin", "Dolphin Group") 
     // { 
     //  new CCategory(1, "Bear", ImageSource.FromFile("bear.png")), 
     //  new CCategory(2, "Elephant", ImageSource.FromFile("elephant.png")), 
     //  new CCategory(3, "Dog", ImageSource.FromFile("dog.png")), 
     //  new CCategory(4, "Cat", ImageSource.FromFile("cat.png")), 
     //  new CCategory(5, "Squirrel", ImageSource.FromFile("squirrel.png")) 
     // }, 

我的问题是我想加入到这个类通过一个循环。所以我很容易能够与添加CCategoryGroup:

cCategory.Add(new CCategoryGroup(name, value) 

如何添加到CCategory构造如前所示?

foreach (XElement catelement in xmlDoc.Descendants(xmlNS + "Category")) 
     { 

      cCategory.Add(new CCategoryGroup(catelement.Element(xmlNS + "Name").Value, catelement.Element(xmlNS + "Name").Value){ 
       foreach (XElement subcatelement in xmlDoc.Descendants(xmlNS + "SubCategory")) 
       { 
        i++; 

        new CCategory(i, subcatelement.Element(xmlNS + "Name").Value, "", subcatelement.Element(xmlNS + "URL").Value); 
       } 
      }); 
     } 

我解析XML并尝试将结果添加到类中。显然这不起作用。但是我正在尝试做的一个样本。对cCategoryGroup的第一个“.add”效果很好,它的构造函数CCategory我不能像在注释掉的代码中那样添加。

+0

你可以编译的是将缺少的第四个参数添加到'CCategory'构造函数调用中。你在寻找不同的东西还是不适合你? –

+3

也停止用'C'预处理所有内容。它使得类和参数名难以阅读,而且在强类型语言中不是必需的。 –

+0

是的,我期待通过循环运行它。我知道注释掉的代码有效,但我基本上试图使用“.add”添加到类和构造函数中。我如何使用“.add”添加到构造函数中? –

回答

0

不,你不能将集合初始化像中使用一个循环,但你可以做到这一点没有初始化:

foreach (XElement catelement in xmlDoc.Descendants(xmlNS + "Category")) 
{ 

    CCategoryGroup categoryGroup = new CCategoryGroup(catelement.Element(xmlNS + "Name").Value, catelement.Element(xmlNS + "Name").Value; 
    cCategory.Add(categoryGroup); 

    foreach (XElement subcatelement in xmlDoc.Descendants(xmlNS + "SubCategory")) 
    { 
     i++; 
     categoryGroup.Add(new CCCategory(i, subcatelement.Element(xmlNS + "Name").Value, "", subcatelement.Element(xmlNS + "URL").Value)); 
    } 
} 

注意,一个初始化刚刚被翻译成由一系列Add电话编译器,所以功能上和循环中添加没有区别。

+0

非常感谢! –