-1

コードを使用しましたが、エラーが発生しました。つまり、
拡張メソッドは最上位の静的クラスで定義する必要があります。StringHelpersネストされたクラスです

namespace Figreplace2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FileInfo n = new FileInfo(textBox1.Text);

            StringBuilder newFile = new StringBuilder();

            string temp = " ";

            string[] file = File.ReadAllLines(textBox1.Text);
        }

    public static class StringHelpers
    {
        public static string Replace(this string s)
        {
            Dictionary<string, string> replacements = new Dictionary<string, string>();

            //replacements.Add("ID1", "NewValue");
            replacements.Add("ID2", "NewValue2");
            // ... further replacement entries ...

            foreach (string line in file)
            {
                bool replacementMade = false;
                foreach (var replacement in replacements)
                {
                    if (line.StartsWith(replacement.Key))
                    {
                        string newString = s;
                        temp = line.Replace(string.Format("{0}   :{1}", replacement.Key, replacement.Value));

                        newFile.Append(temp + "\r\n");

                        continue;
                        return newString;
                    }
                    newFile.Append(line + "\r\n");

                    replacementMade = true;

                  //  break;

                }
                if (!replacementMade)
                {
                    File.WriteAllText(@"D:\madhu\test2\23.txt", newFile.ToString());
                }

            }
        }



    }
}
4

3 に答える 3

1

StringHelpersエラー メッセージは非常に明確です: の宣言をクラスの外に移動する必要がありますForm1(ほとんどの場合、新しいファイル内StringHelpers.cs)。

注意: 「ネストされた」クラスは、別のクラスの「内部」にあるクラスであり、拡張メソッドには使用できません。

于 2013-09-11T11:13:11.867 に答える
1

エラー メッセージが示すように、「拡張メソッドは最上位の静的クラスで定義する必要があります。StringHelpers はネストされたクラスです: Form1.

namespace Figreplace2
{  
    public partial class Form1 : Form
    {
        // get it out of this class
    }

    public static class StringHelpers
    {
        public static string Replace(this string s)
        {
            // ...
        }
    }
}
于 2013-09-11T11:13:58.250 に答える
1

あなたの方法全体StringHelpers Replaceがめちゃくちゃです。

file, temp, は何newFileですか?

それらは使用されていますが、定義されていません

于 2013-09-11T11:15:36.110 に答える