调用我的 CreateFile 方法 -> 非静态字段需要对象引用
calling my CreateFile Method -> An object refference is required for non-static field
我是 C# 新手。这是我的问题的一个小例子。如何在静态方法中调用方法,在本例中为 Main
?这是错误
An object reference is required for non-static field...
怎么了?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string path = @"c:\";
string filename = "lsdfkjg.txt";
CreateFile(path, filename);
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
public void CreateDirectory(string path, string filename)
{
string pathString = System.IO.Path.Combine(path, filename);
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
}
public void CreateFile(string path, string filename)
{
string pathstring = System.IO.Path.Combine(path, filename);
if (!System.IO.File.Exists(pathstring))
{
System.IO.File.Create(pathstring);
}
}
}
}
使您的方法 CreateFile 静态化
public void CreateFile(string path, string filename)
至
public static void CreateFile(string path, string filename)
我是 C# 新手。这是我的问题的一个小例子。如何在静态方法中调用方法,在本例中为 Main
?这是错误
An object reference is required for non-static field...
怎么了?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string path = @"c:\";
string filename = "lsdfkjg.txt";
CreateFile(path, filename);
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
public void CreateDirectory(string path, string filename)
{
string pathString = System.IO.Path.Combine(path, filename);
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
}
public void CreateFile(string path, string filename)
{
string pathstring = System.IO.Path.Combine(path, filename);
if (!System.IO.File.Exists(pathstring))
{
System.IO.File.Create(pathstring);
}
}
}
}
使您的方法 CreateFile 静态化
public void CreateFile(string path, string filename)
至
public static void CreateFile(string path, string filename)