调用类时出现C#错误

时间:2016-09-30 10:49:25

标签: c# .net class

我学会了基础,现在我想学习C#中的OOP 我有这个代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace uceni_cs
{
    class Zdravic
    {
        public void pozdrav()
        {
            Console.WriteLine("Ahoj světe ! ");
        }
    }

}

但是当我尝试使用此代码调用它时

namespace uceni_cs
{
    class Zdravic
    {
        public void pozdrav()
        {
            Console.WriteLine("Ahoj světe ! ");
        }
    }
    Zdravic trida = new Zdravic();
}

代码Zdravic trida = new Zdravic(); 是错误。命名空间不能直接包含字段或方法等成员。 我做错了什么?我只想打电话给全班。 感谢

3 个答案:

答案 0 :(得分:3)

在C#中没有这样的全局变量,所以你不能创建不属于任何类的Zdravic类型的新实例。

我建议你阅读General Structure of a C# Program和c#Classes and Structs

答案 1 :(得分:1)

您需要为应用程序创建一个入口点并在那里实例化该类。

class EntryPoint
{
    static void Main()
    {
        Zdravic trida = new Zdravic();

        trida.pozdrav();
    }
}

答案 2 :(得分:0)

在main方法中创建类对象,然后使用该对象使用类属性。

 Zdravic trida = new Zdravic();

在程序/应用程序的主要方法中。