在 C# 中调用子程序

Call a subroutine in C#

谁能帮帮我 - 我是 C# 控制台应用程序的新手,正在尝试定义一个子例程来替换文件中的文本字符串。

不过我一直收到错误消息:

Error CS0119 'Program.Main(string[])' is a method, which is not valid in the given context SSReplace d:\users\mtait\documents\visual studio 2015\Projects\SSReplace\SSReplace\Program.cs

感谢您的帮助,

马克

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Text.RegularExpressions;

namespace SSReplace
{
class Program
{
    static void Main(string[] args)
    {
        SSReplace.Program.Main.ReplaceInFiles("D:\users\mtait\documents\visual studio 2015\Projects\SSReplace\test_fic_ISUK.txt", "Begin", "Begin2");
    }

    /// <summary>
    /// Replaces text in a file.
    /// </summary>
    /// <param name="filePath">Path of the text file.</param>
    /// <param name="searchText">Text to search for.</param>
    /// <param name="replaceText">Text to replace the search text.</param>
    public void ReplaceInFiles(string filePath, string searchText, string replaceText)
    {
        StreamReader reader = new StreamReader(filePath);
        string content = reader.ReadToEnd();
        reader.Close();

        content = Regex.Replace(content, searchText, replaceText);

        StreamWriter writer = new StreamWriter(filePath);
        writer.Write(content);
        writer.Close();
    }

}
}

您需要将您的方法标记为静态:

public static void ReplaceInFiles

静态方法不能调用实例方法,因为没有创建Program的实例。

要调用该方法,只需使用它的名称 ReplaceInFiles,因为它在同一个命名空间和同一个 class 中。不需要在它之前使用完整的SSReplace.Program.Main

来自 C# 规范:

A method declared with a static modifier is a static method. A static method does not operate on a specific instance and can only directly access static members.

A method declared without a static modifier is an instance method. An instance method operates on a specific instance and can access both static and instance members. The instance on which an instance method was invoked can be explicitly accessed as this. It is an error to refer to this in a static method.

首先:在 C# 中没有子例程这样的东西,它被称为 方法

第二:方法(与任何其他成员一样)在 class 中定义,因此属于 实例 class 或 class 本身 static 成员)。因此改为这样写:

var p = new Program();  // create a new instance of Program
p.ReplaceInFiles(myFile, "Begin", "Begin2"); // call the method on that instance

因为您已经 命名空间 SSReplace 中,您也可以从代码中省略该部分。

或者制作你的方法static。然后你可以这样称呼它:

Program.ReplaceInFiles(myFile, "Begin", "Begin2");

请注意,Main-方法既没有名称空间也没有名称。然而,即使 Program 部分也是可选的,因此以下内容也有效:

ReplaceInFiles(myFile, "Begin", "Begin2");