C# - 在for循环中创建类 [英] C# - Making classes in a for loop

查看:660
本文介绍了C# - 在for循环中创建类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class player 
{
公共字符串名称;
public int rating;






这些类的数量取决于指定的用户金额 numberOfPlayers 。所以我的第一反应是创建一个for循环来做到这一点。即:

$ p $ for(int i = 0; i< numberOfPlayers; i ++)
{
//在这里创建类
}

但是,我需要能够单独访问这些类后来使用他们的个人数据 - 就像他们已经被放入一个数组。我将如何去做一些类可以单独访问?

解决方案

您使用列表< T> 变量,其中T是你的班级

  List< Player> players = new List< Player>(); 
for(int i = 0; i< numberOfPlayers; i ++)
{
Player p = new Player();
p.Name = GetName();
p.rating = GetRating();
players.Add(p);

当然,GetName和GetRating应该被你的代码取代,将它们添加到单个播放器中。

List< T>
中获取数据没有任何区别如果(players.Count> 0)
{
Player pAtIndex0 =玩家[0];
....

$ / code $ / pre

您可以在 List class上的MSDN页面


I have this class:

class player
{
  public string name;
  public int rating;

{

The number of these classes made is dependant on a user specified amount numberOfPlayers. So my first reaction was to create a for loop to do this. i.e:

for (int i = 0; i< numberOfPlayers; i++)
{
    //create class here
}

However, I need to be able to access these classes individually when later using their individual data - almost like they've been put into an array. How would I go about making a number of classes of which can be accessed individually?

解决方案

You use a List<T> variable where T is your class

List<Player> players = new List<Player>();
for (int i = 0; i< numberOfPlayers; i++)
{
    Player p = new Player();
    p.Name = GetName();
    p.rating = GetRating();
    players.Add(p);
}

Of course GetName and GetRating should be substituded by your code that retrieves these informations and add them to the single player.

Getting data out of a List<T> is in no way very different from reading from an array

if(players.Count > 0)
{
    Player pAtIndex0 = players[0];
    ....
}

You can read more info at MSDN page on List class

这篇关于C# - 在for循环中创建类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆