首页 > 解决方案 > 将随机数写入文本文件,C Sharp?

问题描述

我正在尝试将随机数 1 到 10 写入文本文件,但我并不真正了解如何。这些错误代码是什么意思?

这是我到目前为止的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace Random_Number_File_Writer
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void btn_Save_Click(object sender, EventArgs e)
    {
        int randomNumber = 0;


        StreamWriter outputFile;


        int number = int.Parse(Form1.Text);

        if (saveFile.ShowDialog() == DialogResult.OK)
        {

            outputFile = File.CreateText(saveFile.FileName);


            Random Rand = new Random();

            for (int count = 0; count < number; count++)
            {

                randomNumber = Rand.Next(1, 11);


                outputFile.WriteLine(randomNumber);


                MessageBox.Show("File saved in path:" + saveFile.FileName);
            }
               outputFile.Close();
        }
        else
        {

            MessageBox.Show("Operation Cancelled");
        }
    }

    private void btn_Clear_Click(object sender, EventArgs e)
    {
        // Clear the TextBox.
        Form1.Text = "";
    }

    private void btn_Exit_Click(object sender, EventArgs e)
    {

        this.Close();
    }
}

}

这些是我得到的错误:

错误 CS0120 非静态字段、方法或属性“Form.Text”需要对象引用

错误 CS0103 当前上下文中不存在名称“saveFile”

错误 CS0103 当前上下文中不存在名称“saveFile”

错误 CS0103 当前上下文中不存在名称“saveFile”

错误 CS0120 非静态字段、方法或属性“Form.Text”需要对象引用

标签: c#

解决方案


Error CS0120 An object reference is required for the non-static field, method, or property 'Form.Text'

您正在静态调用该类并访问非静态变量。将此更改为this.Text. 这将获取类的当前对象,在您的情况下为 Form1。

Error CS0103 The name 'saveFile' does not exist in the current context

您正在引用一个名为的变量saveFile,但是在使用它之前您还没有声明它。

例如

object saveFile = new object()object正确的类型在哪里。

在您的情况下,我认为您需要 saveFile 为 fileDialog 类型,请参阅文档: https ://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.filedialog?view=netframework-4.8


推荐阅读