Läs på engelska

Dela via


Kompilatorfel CS0116

Ett namnområde får inte innehålla medlemmar direkt, till exempel fält eller metoder.

Ett namnområde kan innehålla andra namnområden, structs och klasser. Mer information finns i nyckelordsartikeln för namnområdet .

Exempel

Följande exempel gör att Visual Studio flaggar delar av koden som i strid med CS0116. Om du försöker skapa den här koden blir det byggfel:

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

Observera att i C# måste metoder och variabler deklareras och definieras inom en struct eller klass. Mer information om programstrukturen i C# finns i artikeln Allmän struktur för ett C#-program . Åtgärda det här felet genom att skriva om koden så att alla metoder och fält finns i antingen en struct eller en klass:

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

Se även