c# - 将随机数写入文本文件,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”需要对象引用
解决方案
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
推荐阅读
- visual-studio-code - 双击括号内
- d3.js - D3单杠排序
- outsystems - outsystems 如何在没有 Mac 和 Xcode 的情况下在 P10 版本中开发 iOS 移动应用程序
- angular - 错误:{ 错误:未捕获(在承诺中):错误:无法匹配任何路由。URL 段:'fontawesome-webfont.woff2'
- c++ - 捕获/抑制发送到 std::cout 的 OpenCV 警告
- python - 我有一个匈牙利文本 ISO-8859-2,我会将文本读入文件但在 Python3 中不起作用
- asp.net-mvc-4 - 在 IQueryable Result 中过滤 DateTime
- c# - c# linq List 属性和分组依据
- meteor - 问:如何加快流星构建/安装包的速度?
- asp.net-mvc-5 - 将选定行从 Telerik Grid 返回到控制器的最佳方法是什么