コンパイラ エラー CS0116
名前空間にフィールドやメソッドのようなメンバーを直接含めることはできません。
名前空間には、他の名前空間、構造体、およびクラスを含めることができます。 詳細については、namespace キーワードの記事を参照してください。
例
次のサンプルでは、コードの一部が CS0116 に違反しているというフラグを Visual Studio で立てます。 このコードをビルドしようとすると、ビルドに失敗します。
// CS0116.cs
namespace x
{
// A namespace can be placed within another namespace.
using System;
// These variables trigger the CS0116 error as they are declared outside of a struct or class.
public int latitude;
public int longitude;
Coordinate coord;
// Auto-properties also fall under the definition of this rule.
public string LocationName { get; set; }
// This method as well: if it isn't in a class or a struct, it's violating CS0116.
public void DisplayLatitude()
{
Console.WriteLine($"Lat: {latitude}");
}
public struct Coordinate
{
}
public class CoordinatePrinter
{
public void DisplayLongitude()
{
Console.WriteLine($"Longitude: {longitude}");
}
public void DisplayLocation()
{
Console.WriteLine($"Location: {LocationName}");
}
}
}
C# では、メソッドや変数を構造体またはクラス内で宣言して定義する必要があります。 C# のプログラム構造の詳細については、「C# プログラムの一般構造」の記事を参照してください。 このエラーを修正するには、すべてのメソッドとフィールドが構造体またはクラスのいずれかに含まれるようにコードを書き直します。
namespace x
{
// A namespace can be placed within another namespace.
using System;
// These variables are now placed within a struct, so CS0116 is no longer violated.
public struct Coordinate
{
public int Latitude;
public int Longitude;
}
// The methods and fields are now placed within a class, and the compiler is satisfied.
public class CoordinatePrinter
{
Coordinate coord;
public string LocationName { get; set; }
public void DisplayLatitude()
{
Console.WriteLine($"Lat: {coord.Latitude}");
}
public void DisplayLongitude()
{
Console.WriteLine($"Longitude: {coord.Longitude}");
}
public void DisplayLocation()
{
Console.WriteLine($"Location: {LocationName}");
}
}
}
こちらもご覧ください
GitHub で Microsoft と共同作業する
このコンテンツのソースは GitHub にあります。そこで、issue や pull request を作成および確認することもできます。 詳細については、共同作成者ガイドを参照してください。
.NET
フィードバック
https://aka.ms/ContentUserFeedback」を参照してください。
以下は間もなく提供いたします。2024 年を通じて、コンテンツのフィードバック メカニズムとして GitHub の issue を段階的に廃止し、新しいフィードバック システムに置き換えます。 詳細については、「フィードバックの送信と表示