如何创建具有属性的类型列表?

时间:2011-12-15 21:56:30

标签: c# c#-4.0

我想创建一个类型类列表,其中包含我可以添加的属性。

还能够访问这些属性吗?

这是我到目前为止所拥有的。

public class Class1 
{
    enum Player
    {
        Me,
        Opponent
    }

    public class MovesMade
    {
        Player Peep = new Player { };
        //Other properties here
    }

    List<MovesMade> AllMoves = new List<MovesMade> {};

    public void MyFunc() 
    {
        AlllMoves.Add ??

        if (AllMoves.Peep == Player.Me) {

        } 
    }
}

3 个答案:

答案 0 :(得分:0)

要使类的属性可以在其自身之外访问,请将其标记为公共。 以下是您的示例修改,以帮助您入门。

public class Class1 
{
    public enum Player
    {
        Me,
        Opponent
    }    

    List<MovesMade> AllMoves = new List<MovesMade> {};

    public void MyFunc() 
    {
        MovesMade movesMade = new MovesMade();
        movesMade.Peep = Player.Me;
        AlllMoves.Add(movesMade);

        if (movesMade.Peep == Player.Me) {

        } 
    }
}

public class MovesMade
{
    public MovesMade(){

    }
    public Player Peep { get; set; }
    //Other properties here
}

答案 1 :(得分:0)

  1. 您的财产声明不充分。而不是

    public class MovesMade
    {
        Player Peep = new Player { };
    }
    

    执行:

    public class MovesMade
    {
        public Player Peep { get; set; }
    }
    
  2. 要向列表中添加新的MovesMade,请调用构造函数:

    AllMoves.Add(new MovesMade());
    
  3. 如果您想在添加时直接设置Peep,请创建一个带Player的构造函数:

    AllMoves.Add(new MovesMade(Player.Opponent));
    

    或使用对象初始值设定项:

    AllMoves.Add(new MovesMade() { Peep = Player.Opponent });
    

答案 2 :(得分:0)

试试这个:

 MovesMade m = new MovesMade();
 m.Peep = new Player();
 m.Peep.Name = "foo";

 AlllMoves.Add(m);

 foreach(var moves in AlllMoves)
 {
    if (moves.Peep.Name = "Jules")
    {
    }
 }