【问题标题】:C# functions and classes helpC# 函数和类帮助
【发布时间】:2011-08-07 06:28:14
【问题描述】:

说我有

class temp {
  private List<temp3> aList = new List<temp3>();
  public List<temp3> getAList()
  {
     return this.aList;
  }
  public temp() {
  }
}

class temp3 {
  public temp3() {}
}

现在我有另一门课

class temp2 {
  private temp t = new temp();

  t.aList.Add(new temp3()); 
}

t.getAList.Add(new temp3());

真的将 temp3 添加到 temp 类的 aList 中吗?

【问题讨论】:

  • 请重新表述您的问题? “真正添加到临时类中的 aList”是什么意思?请解释一下。
  • 这里的“a”是什么意思...请更改“a”类的名称以澄清它..
  • 我用 temp3 改写了 a
  • temp.aList 是私有的,所以t.aList.Add 不起作用!?为什么您认为temp3不会被添加到列表中?是的,当然会,但在你的情况下,就像我说的那样,aList 是私人成员,无法访问。
  • 你也必须把语句放在一个方法中..你不能直接把它放在一个类中

标签: c# class list function reference


【解决方案1】:

没有。

该行应该是:

 t.getAList().Add(new temp3()); 

EDIT 阅读 cmets 后:将该行放入方法中。

【讨论】:

  • 哎呀,这是一个错字,所以它会将 temp3 添加到 temp 类中的 aList 中吗?
  • 那么,是的。为什么不呢?你测试了吗?
【解决方案2】:

aList 是私有的,您无法通过这种方式访问​​它 t.aList.Add(new temp3()); 。 你应该使用get方法getAList()like this t.getAList.Add(new temp3());

下面的代码做你想做的事

使用系统; 使用 System.Collections.Generic; 使用 System.Linq; 使用 System.Text;

namespace Project4
{
  class temp {
  private List<temp3> aList = new List<temp3>();
  public List<temp3> getAList
  {
     get{return aList;}
      set{aList = value;}
  }
  public temp() {
  }
}

class temp3 {
  public temp3() {}
}

class temp2 {
    public static void Method()
    { 
        temp t = new temp();
        t.getAList.Add(new temp3());
    }

}
}

【讨论】:

    【解决方案3】:

    temp.aList 是私有的,所以不行。您想要做的是向temp 类添加一个属性:

    public List<temp3> AList  
    {  
        get {return aList;}  
        set {aList = value;}  
    }
    

    然后将其用作t.AList.Add(new temp3())

    正如 Akram Shahda 在 cmets 中指出的那样,您必须在类中创建一个方法 为了它。你不能直接在类中使用这样的语句。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-09
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多