【问题标题】:How does C# understand an .txt file as output for the main?C# 如何将 .text 文件理解为 main 的输出?
【发布时间】:2016-09-14 09:29:08
【问题描述】:

main中编写如下代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace text_test
{
class Program
{
    static void Main(string[] args)
     {
       txt_program tt = new txt_program();
        string[] output_txt = tt.txt;
    }
}
}

出现错误:

说明无法将方法组 'txt' 转换为非委托类型 'string[]'。

我应该写什么而不是string[]?调用代码如下:

(与上述相同的系统调用)。

namespace text_test
{

class txt_program

{
    public void txt(string[] args)
    {
        // Take 5 string inputs -> Store them in an array
        // -> Write the array to a text file

        // Define our one ad only variable
        string[] names = new string[5]; // Array to hold the names

        string[] names1 = new string[] { "max", "lars", "john", "iver", "erik" };

        for (int i = 0; i < 5; i++)
        {
            names[i] = names1[i];
        }

        // Write this array to a text file

        StreamWriter SW = new StreamWriter(@"txt.txt");

        for (int i = 0; i < 5; i++)
        {
            SW.WriteLine(names[i]);
        }

        SW.Close();
    }
}
}

【问题讨论】:

  • 也许是tt.txt() 而不是tt.txt? @HimBromBeere 的编辑:tt.txt(args)
  • 它会产生错误没有给出与“txt_program-txt(string[])”所需的形参“args”相对应的参数。就像主要不明白 txt 的输出是 .txt- 文件一样。 @KeyurPATEL
  • 你到底想做什么?函数txt 接受参数args 但从不使用它;此外,它不返回任何内容 (void),因此您不能将其分配给 string[]

标签: c# file main streamwriter.write


【解决方案1】:

如果您只想将数组写入文件

 static void Main(string[] args) {
   string[] namess = new string[] { 
     "max", "lars", "john", "iver", "erik" };

   File.WriteAllLines(@"txt.txt", names);
 }

如果你坚持用流分开类:

class txt_program {
  // () You don't use "args" in the method
  public void txt(){ 
    string[] names = new string[] { "max", "lars", "john", "iver", "erik" };

    // wrap IDisposable (StreamWriter) into using 
    using (StreamWriter SW = new StreamWriter(@"txt.txt")) {
      // do not use magic numbers - 5. 
      // You want write all items, don't you? Then write them  
      foreach (var name in names)
        SW.WriteLine(name);
    }
  }
}

...

static void Main(string[] args){
  // create an instance and call the method
  new txt_program().txt();
}

【讨论】:

    【解决方案2】:

    public void txt(string[] args) { }

    删除参数“string[] args”,不需要。

    这样调用方法 tt.txt();

    void 方法不返回任何值

    所以不要尝试获取字符串数组。

    【讨论】:

      猜你喜欢
      • 2021-12-11
      • 2021-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多