Примечание
Для доступа к этой странице требуется авторизация. Вы можете попробовать войти или изменить каталоги.
Для доступа к этой странице требуется авторизация. Вы можете попробовать изменить каталоги.
Пространство имен не может непосредственно включать такие члены, как поля или методы.
Пространство имен может содержать другие пространства имен, структуры и классы. Дополнительные сведения см. в руководстве по ключевому слову namespace.
Пример
В следующем примере Visual Studio отметит части кода как нарушение CS0116. Попытка выполнить сборку этого кода приведет к сбою:
// 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#. Чтобы устранить эту ошибку, перепишите код так, чтобы все методы и поля содержались в пределах структуры или класса:
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}");
}
}
}