Aracılığıyla paylaş


Derleyici Hatası CS0116

Ad alanı, alanlar veya yöntemler gibi üyeleri doğrudan içeremez.

Ad alanı başka ad alanları, yapılar ve sınıflar içerebilir. Daha fazla bilgi için ad alanı anahtar sözcüğü makalesine bakın.

Örnek

Aşağıdaki örnek, Visual Studio'nun kodun bölümlerini CS0116 ihlali olarak işaretlemesine neden olur. Bu kodu derlemeye çalışmak derleme hatasına neden olur:

// 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# dilinde yöntemlerin ve değişkenlerin bir yapı veya sınıf içinde bildirilmesi ve tanımlanması gerektiğini unutmayın. C# dilinde program yapısı hakkında daha fazla bilgi için C# Programının Genel Yapısı makalesine bakın. Bu hatayı düzeltmek için kodunuzu, tüm yöntemlerin ve alanların bir yapı veya sınıf içinde yer aldığı şekilde yeniden yazın:

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

Ayrıca bkz.