Delen via


Compilerfout CS0116

Een naamruimte kan geen leden zoals velden of methoden rechtstreeks bevatten.

Een naamruimte kan andere naamruimten, structs en klassen bevatten. Zie het trefwoordartikel voor de naamruimte voor meer informatie.

Opmerking

Het volgende voorbeeld zorgt ervoor dat Visual Studio onderdelen van de code markeert als schending van CS0116. Als u deze code probeert te bouwen, resulteert dit in een buildfout:

// 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}");
        }
    }
}

In C# moeten methoden en variabelen worden gedeclareerd en gedefinieerd binnen een struct of klasse. Zie het artikel Algemene structuur van een C#-programma voor meer informatie over de programmastructuur in C#. U kunt deze fout oplossen door de code zo te herschrijven dat alle methoden en velden zich in een struct of een klasse bevinden:

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}");
        }
    }
}

Zie ook