0

私はC#が初めてです。複数のコンピューター インスタンスがあり、それぞれに名前、停止、開始、および再起動のコマンドが関連付けられています。ファイルから情報を読み込みたい。

instancelist[0].Instance_name=Enterprise1だから私はandinstancelist[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++;
}

次のように、引き続き index によって instanceList の要素にアクセスできることに注意してください。

instanceList[0].InstanceStart
于 2013-05-09T00:21:13.590 に答える
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 に答える
0

あなたの質問はかなり漠然としていますが、これが私の答えの試みです。

「インスタンス」という名前のクラスがあるようです。「インスタンス」クラスのインスタンスのリストを作成することをお勧めします。

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

特定の名前の値を見つける必要がある場合は、2 つの方法があります。1 つは、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 に答える