Share via


編譯器錯誤 CS0116

命名空間不能直接包含欄位或方法等成員。

命名空間可以包含其他命名空間、結構及類別。 如需詳細資訊,請參閱 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# 撰寫之程式結構的詳細資訊,請參閱 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}");
        }
    }
}

另請參閱