Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 具有多个对象的数组的数组_C#_Arrays - Fatal编程技术网

C# 具有多个对象的数组的数组

C# 具有多个对象的数组的数组,c#,arrays,C#,Arrays,我对C#真的是个新手。我有多个计算机实例,每个实例都有名称、停止、启动和重新启动命令。我想从文件中读入信息 因此,我想以实例列表[0]结束。实例名称=Enterprise1和实例列表[0]。实例停止=@Enterprise\u停止和实例列表[1]。实例名称=Enterprise5等等。我能想出怎么做申报 public class Instance { public string Instance_name; public string Instance_stop; pu

我对C#真的是个新手。我有多个计算机实例,每个实例都有名称、停止、启动和重新启动命令。我想从文件中读入信息

因此,我想以实例列表[0]结束。实例名称=Enterprise1和
实例列表[0]。实例停止=@Enterprise\u停止
实例列表[1]。实例名称=Enterprise5
等等。我能想出怎么做申报

public class Instance
{
    public string Instance_name;
    public string Instance_stop;

    public string Instance_restart;
    public string Instance_backup;
} 

public static void Main(string[] args)
{
    int num_instances=0;

    /** CAN'T figure out the declaration. I'm currently thinking array of array? */

    System.IO.StreamReader file = new System.IO.StreamReader(@"C......");

    while(true)
    {
        instancelist[num_instance].Instance_name=file.ReadLine();
        instancelist[num_instance].Instance_stop=file.ReadLine();
        // and so on.......
        num_instance++;
    }
}

使用集合而不是数组可能会更好。如果元素的数量发生变化,则更容易处理。在您的例子中,您正在从文件中读取字符串,因此不太可能提前知道列表的大小

但是,您还需要一个DTO类。下面是一些代码(未经测试):


听起来像是要获取这些
实例
对象的集合,每个对象都将从文件中的一组连续行进行解析

我想推荐如下:

// First: a static method to create an Instance object from a few
// consecutive lines in a stream
class Instance
{
    public static Instance ReadFromStream(StreamReader reader)
    {
        var instance = new Instance();
        instance.InstanceName = reader.ReadLine();
        instance.InstanceStop = reader.ReadLine();
        // etc.
        return instance;
    }
}

// Then, elsewhere: use a List<T> (an expandable collection)
// to store all the instances you create from reading the file.
// Note that the 'using' statement automatically closes the file
// for you when you're done.
var instances = new List<Instance>();
using (var reader = new StreamReader(filePath))
{
    while (!reader.EndOfStream)
    {
        instances.Add(Instance.ReadFromStream(reader));
    }
}
// Convention in C# is to use properties instead of fields for something like this
// also, having the class name in the field name is redundant
public class Instance
{
    public string Name {get;set;}
    public string Stop {get;set;}

    public string Restart {get;set;}
    public string Backup {get;set;}
} 

public static void Main(string[] args)
{
    List<Instance> items = new List<Instance>();

    // the using block will close the file handle
    using (System.IO.StreamReader file = new System.IO.StreamReader(@"C......"))
    {
        while(true)
        {
            String name = file.ReadLine(), stop = file.ReadLine(), restart = file.ReadLine(), backup = file.ReadLine();
            if (name == null || stop == null || restart == null || backup == null)
                break; // I didn't test it, but this should work for determining the end of the file
            items.Add(new Instance(){
               Name = name,
               Stop = stop,
               Restart = restart,
               Backup = backup
            });
        }
    }
}
//首先:一个静态方法,用于从几个
//流中的连续行
类实例
{
公共静态实例ReadFromStream(StreamReader)
{
var instance=新实例();
instance.InstanceName=reader.ReadLine();
instance.InstanceStop=reader.ReadLine();
//等等。
返回实例;
}
}
//然后,在其他地方:使用列表(可扩展的集合)
//存储通过读取文件创建的所有实例。
//请注意,“using”语句会自动关闭文件
//当你完成的时候。
var实例=新列表();
使用(var reader=newstreamreader(filePath))
{
而(!reader.EndOfStream)
{
Add(Instance.ReadFromStream(reader));
}
}

你的问题很模糊,但这是我试图回答的问题

显然,您有一个名为“Instance”的类,我建议创建一个“Instance”类实例列表:

using System.Collections.Generic; // Add this to the rest of 'usings' 

public static void Main(string[], args)
{
    // Create a new stream to read the file
    StreamReader SReader = new StreamReader("C:\file.txt");

    // Create a list of 'Instance' class instances
    List<Instance> AllInstances = new List<Instance>();

    // Keep reading until we've reached the end of the stream
    while(SReader.Peek() > 0)
    {
         // Read the line
         string CurrentLine = SReader.ReadLine(); // if you call this multiple times in this loop you proceed multiple lines in the file..

         // Create an new instance of the 'Instance' class
         Instance CurrentInstance = new Instance();

         // Assign the 'Name' property
         CurrentInstance.Name = CurrentLine;

         // Add class instance to the list
         AllInstances.Add(CurrentInstance);
    }

    // Close the stream
    SReader.Close();
}
使用System.Collections.Generic;//将此添加到其余的“使用”
公共静态void Main(字符串[],args)
{
//创建一个新的流来读取文件
StreamReader SReader=新的StreamReader(“C:\file.txt”);
//创建“实例”类实例的列表
List ALINSTANCES=新列表();
//继续读,直到我们到达小溪的尽头
while(SReader.Peek()>0)
{
//读台词
string CurrentLine=SReader.ReadLine();//如果在此循环中多次调用此函数,则会在文件中执行多行操作。。
//创建“instance”类的新实例
实例CurrentInstance=新实例();
//分配“Name”属性
CurrentInstance.Name=CurrentLine;
//将类实例添加到列表中
添加(CurrentInstance);
}
//关闭小溪
SReader.Close();
}
最后,您将有一个“实例”类的列表。有关列表的更多信息:

关于StreamReader:


只有在您提前知道需要多少元素并且不插入或删除元素的情况下,阵列才是真正合适的。即使如此,像列表这样的集合对象通常也是可取的

你可以这样做:

// First: a static method to create an Instance object from a few
// consecutive lines in a stream
class Instance
{
    public static Instance ReadFromStream(StreamReader reader)
    {
        var instance = new Instance();
        instance.InstanceName = reader.ReadLine();
        instance.InstanceStop = reader.ReadLine();
        // etc.
        return instance;
    }
}

// Then, elsewhere: use a List<T> (an expandable collection)
// to store all the instances you create from reading the file.
// Note that the 'using' statement automatically closes the file
// for you when you're done.
var instances = new List<Instance>();
using (var reader = new StreamReader(filePath))
{
    while (!reader.EndOfStream)
    {
        instances.Add(Instance.ReadFromStream(reader));
    }
}
// Convention in C# is to use properties instead of fields for something like this
// also, having the class name in the field name is redundant
public class Instance
{
    public string Name {get;set;}
    public string Stop {get;set;}

    public string Restart {get;set;}
    public string Backup {get;set;}
} 

public static void Main(string[] args)
{
    List<Instance> items = new List<Instance>();

    // the using block will close the file handle
    using (System.IO.StreamReader file = new System.IO.StreamReader(@"C......"))
    {
        while(true)
        {
            String name = file.ReadLine(), stop = file.ReadLine(), restart = file.ReadLine(), backup = file.ReadLine();
            if (name == null || stop == null || restart == null || backup == null)
                break; // I didn't test it, but this should work for determining the end of the file
            items.Add(new Instance(){
               Name = name,
               Stop = stop,
               Restart = restart,
               Backup = backup
            });
        }
    }
}
请注意,如果未找到此类元素,
FirstOrDefault
将返回
null
,在这种情况下,
.Stop
取消引用将引发异常

另一方面,如果您确实希望按名称对整个数据结构进行索引,那么
列表(或数组)可能不是最好的方法。另一个解决办法可以是:

public class Instance2
{
    public string Stop {get;set;}
    public string Restart {get;set;}
    public string Backup {get;set;}
} 

Dictionary<String, Instance2> items = new Dictionary<String, Instance2>();

// ...

items[name] = new Instance2(){Stop = stop,
    Restart = restart,
    Backup = backup};

您有几个选项,如果您事先知道实例的数量,您可以使用数组,但如果不知道,您也可以使用
列表

publicstaticvoidmain(字符串[]args)
{
List instancelist=新列表();
System.IO.StreamReader file=new System.IO.StreamReader(@“C…”);
while(!file.EndOfStream)//而不是while(true),它永远不会停止
{
//即使在数组中,instancelist[i]。Instance_name也将是空指针异常,
//因此,我们创建实例,然后将其添加到列表中
var instance=新实例();
instance.instance_name=file.ReadLine();
//…等等
instancelist.Add(实例);
}
}

我想你说的是“锯齿”数组:这里有一个链接解释了它的用法:您好!我花了一些时间来格式化你的代码,但是将来你应该在发布你的问题之前让你的代码看起来像样一些。(若要一次发布大量代码,请使用“代码示例”选项将所有代码缩进四个空格,使其格式为代码)您实际上没有正确回答OP的问题。。。实例列表不是一组字符串,而是一组实例对象。我喜欢这样,但在将其读入列表后,我需要能够搜索“名称”,并在“停止”中返回值。如果列表未编制索引,我将如何搜索名称并在Stop中返回字符串。也许我只是不明白列表的概念?因为它看起来就像一个长长的对象列表,没有名称、停止、重新启动和备份绑定在一起。更新。列表很容易搜索。我不知道你说的把它们捆绑在一起是什么意思。关联数据块都位于同一对象中。也许在调试器中运行它,您可以看到列表或字典的外观。谢谢您的帮助。我能让它工作!我已经为此工作了好几天了。现在我只需要将我的小部分集成到我收到的大程序中。很高兴能提供帮助。如果你觉得这个答案很有用,你能把它选为“最佳答案”吗?谢谢
public class Instance2
{
    public string Stop {get;set;}
    public string Restart {get;set;}
    public string Backup {get;set;}
} 

Dictionary<String, Instance2> items = new Dictionary<String, Instance2>();

// ...

items[name] = new Instance2(){Stop = stop,
    Restart = restart,
    Backup = backup};
String nameToFind = "...";
String stop = items[nameToFind].Stop;
public static void main(string[] args)
{
    List<Instance> instancelist = new List<Instance>();

    System.IO.StreamReader file = new System.IO.StreamReader(@"C......");
    while (! file.EndOfStream ) // rather than while(true) which never stops
    {
          // Even if this were in an array, instancelist[i].Instance_name would be a null pointer exception,
          // So we create the instance and then add it to the list
          var instance = new Instance(); 
          instance.Instance_name = file.ReadLine();
          //... etc

          instancelist.Add(instance);
    }
}