0

我对 C# 真的很陌生。我有多个计算机实例,每个实例都有一个与每个实例关联的名称、停止、启动和重新启动命令。我想从文件中读取信息。

所以我想以instancelist[0].Instance_name=Enterprise1instancelist[0].Instance_stop=@Enterprise_stop等等结束instancelist[1].Instance_name=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++;
    }
}
4

5 回答 5

2

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

但是,您还需要一个 DTO 类。所以这里有一些代码(未经测试):

// DTO Class
public class Instance
{
   public string Instance_Start { get; set; }
   public string Instance_Stop { get; set; }
}

var instanceList = new List<Instance>;
var file = new System.IO.StreamReader(myFile);

while(!file.EndOfStream)
{
    var instance = new Instance
    {
        Instance_Start = file.Readline();
        Instance_Stop = file.Readline();
    };

    instanceList.Add(instance);
    num_instance++;
}

请注意,您仍然可以按索引访问 instanceList 上的元素,如

instanceList[0].InstanceStart
于 2013-05-09T00:21:13.590 回答
0

你的问题相当模糊,但这是我试图回答的问题。

显然你有一个名为“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();
}

最后,您将获得一个“实例”类列表。有关列表的更多信息:

http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx

关于 StreamReader:

http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx

于 2013-05-09T00:28:09.183 回答
0

只有当您提前知道需要多少并且不会插入或删除元素时,数组才是真正合适的。即便如此,像 List 这样的集合对象通常更可取。

你可以这样做:

// 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
            });
        }
    }
}

如果您需要能够找到特定名称的值,有两种方法。一种是循环比较 Name 属性并存储 List 索引。这样做的更惯用的方式(尽管对于新手来说并不容易阅读)是:

String nameToFind = "...";
String stop = items.Where(item => item.Name == nameToFind).FirstOrDefault().Stop;

请注意,如果没有找到这样的元素,FirstOrDefault它将返回,在这种情况下,取消引用将引发异常。null.Stop

另一方面,如果您真的希望整个数据结构按名称索引,a List(或数组)可能不是最好的方法。另一种解决方案可能是:

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};

使用这样的数据结构,按名称查找效率要高得多(O(log(n))与 相比O(n))。你会这样做:

String nameToFind = "...";
String stop = items[nameToFind].Stop;
于 2013-05-09T00:29:00.517 回答
0

你有几个选择,如果你事先知道实例的数量,你可以使用数组,否则你也可以使用List<Instance>.

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);
    }
}
于 2013-05-09T00:31:17.277 回答
0

听起来您想获取这些Instance对象的集合,每个对象都将从文件中的一组连续行中解析出来。

我会推荐这样的东西:

// 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));
    }
}
于 2013-05-09T00:26:16.383 回答