実現したいこと
.NET 6 の C# テンプレートを使用してデリゲートを記述したい。
前提
Visual Studioを用いてC#の勉強をしています。
.NET 6 の C# テンプレートを使用してデリゲードのサンプルプログラムを記述したところ以下のエラーが発生しました。
発生している問題・エラーメッセージ
(7行目 // 1つ目の処理) CS8803:トップレベルのステートメントは、名前空間および型の宣言の前に記述する必要があります。
試したこと
.NET 6 の C# テンプレートを使用せずに記述するとエラーが起きない。
該当のソースコード(C# テンプレートを使用)
// See https://aka.ms/new-console-template for more information // デリゲートの宣言 delegate void Action(int a); // 1つ目の処理 static void Func1(int a) { Console.WriteLine("a={0}", a); } // 2つ目の処理 static void Func2(int a) { Console.WriteLine("a*2={0}", a * 2); } // 3つ目の処理 static void Func3(int a) { Console.WriteLine("a*3={0}", a * 3); } static void Main(string[] args) { // デリゲートaの作成 Action a = new Action(Func1); // 処理の追加 a += new Action(Func2); a += new Action(Func3); // 処理の実行 a(3); }
該当のソースコード(C# テンプレートを使用しない)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SampleEx702 { class Program { // デリゲートの宣言 delegate void Action(int a); // 1つ目の処理 static void Func1(int a) { Console.WriteLine("a={0}",a); } // 2つ目の処理 static void Func2(int a) { Console.WriteLine("a*2={0}", a * 2); } // 3つ目の処理 static void Func3(int a) { Console.WriteLine("a*3={0}", a * 3); } static void Main(string[] args) { // デリゲートaの作成 Action a = new Action(Func1); // 処理の追加 a += new Action(Func2); a += new Action(Func3); // 処理の実行 a(3); } } }
補足情報(FW/ツールのバージョンなど)
Visual Studio 2022
C#コンソールアプリケーション
.NET 6 の C# テンプレート

回答1件
あなたの回答
tips
プレビュー